设置writable为true后仍无法赋值Redux只读属性的问题求助
问题分析与解决办法
核心原因
Redux存储的状态对象是不可变且只读的(通常被Object.freeze冻结),你直接将existing(Redux状态)赋值给response并修改其属性,本质是在尝试修改只读的Redux原状态,所以触发TypeError。你一开始对空对象response设置可写属性的操作完全无效,因为之后直接把response替换成了existing。
解决步骤
- 永远不要直接修改Redux原状态,必须创建原状态的深拷贝,在拷贝对象上进行修改
- 修正代码中变量引用的错误(比如
copySecGroupOrder的参数应该是existing.secGroupOrder而非未定义的全局变量) - 确保所有属性修改都作用在拷贝后的对象上
修改后的代码
function formatData(initialResponse, existing) { let response; if (existing) { // 深拷贝existing,避免直接修改Redux原状态 response = structuredClone(existing); // 修正参数:使用existing的secGroupOrder进行拷贝 let newOrder = copySecGroupOrder(existing.secGroupOrder); newOrder.forEach(group => { let existingGroup = existing.secGroups[group.name]; if (existingGroup && existingGroup.sections) { // 嵌套对象也要拷贝,避免引用原状态的内容 group.sections = structuredClone(existingGroup.sections); } }); // 修改拷贝后的对象属性,不会触发只读错误 response.secGroupOrder = newOrder; } else { response = { secGroupOrder: copySecGroupOrder(initialResponse.secGroupOrder), secGroups: {}, sections: initialResponse.sections, fields: copyFields(initialResponse.fields) }; } response.secGroupOrder.forEach(group => { response.secGroups[group.name] = group; if (!group.sections) { group.sections = {}; } }); if( response.secGroups['Comp 1']){ response.secGroups['Comp 1'].component = Cmp1; } if (response.secGroups['Comp 2']) { response.secGroups['Comp 2'].component = Cmp2; } return response; }
关键细节说明
- 使用
structuredClone进行深拷贝:这是ES2022原生API,能处理大部分嵌套对象、数组的拷贝;如果你的环境不支持,可以用递归拷贝函数或者第三方库(如Lodash的_.cloneDeep)代替 - 嵌套对象也要拷贝:比如
group.sections,如果直接引用existingGroup.sections,后续修改仍会影响Redux原状态,必须也做拷贝 - 修正变量引用:原代码中
copySecGroupOrder(secGroupOrder)的secGroupOrder未定义,应该是existing.secGroupOrder或initialResponse.secGroupOrder,根据实际业务逻辑调整
内容的提问来源于stack exchange,提问作者copenndthagen
相关产品推荐
相关产品推荐

