配置编辑器通常需要在用户点击保存之前保留一个可恢复的原始版本。如果只复制对象第一层,嵌套数组和对象仍可能被共享,取消编辑时就无法还原。structuredClone 提供浏览器原生的结构化克隆能力。本文以配置编辑器和撤销记录为例,讨论数据复制、循环引用、可转移对象以及不能克隆的类型。
下列代码块按各节独立展示,实际接入时应结合相应的样式、脚本或组件文件。
1. 浅拷贝为何破坏取消编辑
下面的配置项包含嵌套通知对象。对象展开只能复制第一层,修改副本的 notification.enabled 仍可能改变原对象。对普通结构化数据,需要建立独立快照。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/6b704478e0db7d11659844d36dd864f443885ef2">
<section class="notification-editor"><h2>通知配置</h2><label><input type="checkbox" data-notify>接收通知</label><button type="button" data-cancel>取消编辑</button></section>
</div>
const saved = {
notification: {
enabled: true } };
const shallow = {
...saved };
shallow.notification.enabled = false;
console.assert(saved.notification.enabled === false);
const draft = structuredClone(saved);
draft.notification.enabled = true;
console.assert(saved.notification.enabled === false);
2. 创建明确的编辑会话
将保存版本与编辑草稿分开,取消操作只恢复草稿,提交成功才接受服务器确认的数据。不要把表单元素、回调或整个组件实例放进待复制的业务对象。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/9968e81dcb63c3d5b02eeafcc6bb7543f8892c68">
<form data-profile-editor><label>显示名称<input name="name" required></label><button type="submit">保存</button><button type="button" data-restore>恢复</button></form>
</div>
function createSession(initial) {
let committed = structuredClone(initial);
let draft = structuredClone(committed);
return {
getDraft: () => draft,
restore() {
draft = structuredClone(committed); },
accept(serverValue) {
committed = structuredClone(serverValue);
draft = structuredClone(committed);
}
};
}
3. 日期、集合与 JSON 转换的区别
JSON 序列化会把 Date 转为字符串,并且 Map、Set 默认无法按原结构保存。结构化克隆可以复制这些内置类型,但这并不改变 HTTP 接口所采用的 JSON 契约。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/35cd1547a7cf0e7e54d4c946272cfaec75538f9a">
<dl class="schedule-preview"><dt>更新时间</dt><dd data-last-edit></dd><dt>项目标签</dt><dd data-tag-count></dd></dl>
</div>
const state = {
updatedAt: new Date(), labels: new Set(['draft']), flags: new Map([['review', true]]) };
const snapshot = structuredClone(state);
console.assert(snapshot.updatedAt instanceof Date);
console.assert(snapshot.labels instanceof Set);
console.assert(snapshot.flags.get('review') === true);
4. 循环引用不等于无限递归
某些本地模型含父子引用或共享子对象。structuredClone 能保持这些引用关系在副本内部的结构,不会把循环引用直接递归到栈溢出。不过 JSON 接口仍不能直接序列化循环对象。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/f200d8339bffbdc1bbf2701d37d5331d490f24ab">
<section class="tree-editor"><h2>目录结构</h2><ul><li>项目目录<ul><li>配置目录</li></ul></li></ul></section>
</div>
const parent = {
name: 'root', children: [] };
const child = {
name: 'config', parent };
parent.children.push(child);
const copy = structuredClone(parent);
console.assert(copy !== parent);
console.assert(copy.children[0].parent === copy);
5. 识别不能克隆的值
函数、DOM 节点不能通过结构化克隆复制,包含它们的对象可能抛出 DataCloneError。自定义类实例也不保证保留原型链、访问器或属性描述符。应先从运行时对象提取明确的业务字段。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/a0b72e92a66a0430564de512a3a06595008bf2cf">
<section class="export-panel"><button type="button" data-export>生成数据快照</button><p data-clone-error role="alert"></p></section>
</div>
function trySnapshot(value) {
try {
return {
ok: true, value: structuredClone(value) }; }
catch (error) {
if (error?.name === 'DataCloneError') return {
ok: false, message: '数据包含不能复制的字段' };
throw error;
}
}
6. 实现具有容量限制的撤销栈
每次确定的编辑操作开始前记录一个独立快照,而不是每次读取视图都复制。给撤销记录设置上限;对于文本输入可在一次编辑事务结束时生成快照,避免按每个字符保存整份模型。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/3771b3b79e40ed7d709371ccd07c25a551db2db8">
<div class="edit-toolbar"><button type="button" data-undo>撤销</button><output data-history-size>0</output></div>
</div>
function createUndoHistory(limit) {
if (!Number.isInteger(limit) || limit < 1) throw new RangeError('invalid limit');
const history = [];
return {
push(value) {
history.push(structuredClone(value));
if (history.length > limit) history.shift();
},
undo() {
return history.pop(); },
get size() {
return history.length; }
};
}
7. 二进制数据复制与所有权转移
ArrayBuffer 可以被复制,也可以通过 transfer 选项转移。转移后原缓冲区被分离,不能再用于原来的编辑预览。用于撤销快照时通常需要复制;只有明确移交所有权的场景才考虑 transfer。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/a5d37d9a44d7b56c061d41212d31f619d55f8f63">
<section class="binary-editor"><h2>二进制文件处理</h2><input type="file" data-binary-file><output data-buffer-size></output></section>
</div>
async function prepareBinary(file) {
const original = await file.arrayBuffer();
const retained = structuredClone(original);
const moved = structuredClone(original, {
transfer: [original] });
return {
retained, moved };
}
8. 避免把深拷贝当成响应式更新策略
如果每次修改一个复选框就深拷贝几千条记录,会产生不必要的分配。局部更新只复制发生变化的路径即可;完整快照应服务于明确的业务节点,例如撤销检查点。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/0d0986a75b9221d2886d09123922ea7659736438">
<section class="feature-list"><label><input type="checkbox" data-feature="audit">开启审计</label><label><input type="checkbox" data-feature="report">开启报告</label></section>
</div>
function setFeature(state, key, enabled) {
return {
...state, features: {
...state.features, [key]: enabled } };
}
9. 不要直接克隆框架代理对象
响应式框架可能用 Proxy 包装对象。Proxy 不是结构化克隆支持的类型。应在业务边界建立普通数据 DTO,明确选取字段,不能依赖克隆框架内部运行状态。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/14c614a55eeb393861f2bd9f11ed2e369dc47b43">
<section class="draft-summary"><h2>待保存配置</h2><p data-display-name></p><p data-enabled-state></p></section>
</div>
function toDraftDTO(model) {
return {
name: String(model.name), enabled: Boolean(model.enabled), tags: Array.from(model.tags, String) };
}
function capture(model) {
return structuredClone(toDraftDTO(model)); }
10. 设计针对引用隔离的测试
测试重点不是两个对象的 JSON 字符串相同,而是修改嵌套值后原对象不变,以及共享引用在新对象内部仍保持正确关系。还应覆盖空值、特殊内置对象和克隆失败。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/2e6f65d0dd4013766bbf6058b7f840329f3ffb02">
<section class="snapshot-checks"><h2>编辑器验证</h2><ul><li>取消编辑后恢复原值</li><li>连续撤销返回前一版本</li><li>错误快照不会覆盖原数据</li></ul></section>
</div>
function verifySnapshot() {
const original = {
rows: [{
value: 1 }] };
const copy = structuredClone(original);
copy.rows[0].value = 2;
if (original.rows[0].value !== 1) throw new Error('snapshot is not isolated');
}
总结
结构化克隆适合建立独立数据快照,而不是替代所有对象更新方式。先明确可复制的数据模型,区分普通复制与所有权转移,并为撤销历史设置容量和提交边界,才能在复杂编辑器中保持数据一致。