You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Array.push抛出TypeError:Cannot add property 0, object is not extensible问题求助

解决"Cannot add property 0, object is not extensible"错误

这个错误的核心原因是你要操作的curNode.children数组被设置为不可扩展了——也就是说JS引擎不允许给这个数组添加新元素。这种情况通常是因为该数组(或者它所属的curNode对象)被Object.freeze()、Object.seal()或Object.preventExtensions()处理过,或是从某些框架(比如React的state返回值、Redux的state)中获取的冻结对象。

以下是两种直接可行的解决方法:

方法1:替换为新的可扩展数组

直接把原数组替换成一个新的可扩展数组,再添加元素:

// 方式A:用扩展运算符复制后添加元素
curNode!.children = [...curNode!.children!, {
    name: newNodeName,
    children: []
}];

// 方式B:先复制再push,逻辑更清晰
const updatedChildren = [...curNode!.children!];
updatedChildren.push({
    name: newNodeName,
    children: []
});
curNode!.children = updatedChildren;

方法2:如果curNode本身不可扩展

如果curNode对象整体被冻结/密封,连修改children属性都不允许,那需要创建一个完整的新对象:

// 复制原对象的所有属性,生成新的可扩展对象
const newCurNode = { ...curNode! };
// 给新对象的children添加元素
newCurNode.children = [...newCurNode.children!, {
    name: newNodeName,
    children: []
}];
// 之后使用newCurNode替代原来的curNode

你可以先通过console.log(Object.isExtensible(curNode!.children!))验证数组的可扩展性——如果返回false,就说明数组确实被限制扩展了,用上面的方法就能解决。

内容的提问来源于stack exchange,提问作者jeril

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 04:05:41