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

Error 6412:无法赋值给只读属性的问题排查与解决

更新State Model时遇到TypeError:无法赋值给只读属性'decisionDate'

问题详情

报错信息:

core.mjs:6412 ERROR TypeError: Cannot assign to read only property 'decisionDate' of object '[object Object]'

原代码(报错行标注-->):

@Action(ClerkAction.Review.UpdateSelectedDate)  
onUpdateSelectedDate(ctx: StateContext<ClerkStateModel>, action: ClerkAction.Review.UpdateSelectedDate) {
    const DocumentList = ctx.getState().request.documents;
    const DocumentIndex = DocumentList.findIndex(item => item.guid === action.documentGuid);  
--> DocumentList[DocumentIndex].decisionDate = action.newDate;  

    ctx.patchState({ 
        request: {
            ...ctx.getState().request,
            documents: DocumentList
        }        
    });

    ctx.dispatch(new NotificationAction.Loading(false));
}  

问题原因

状态管理库(如NgRx)中的State Model对象默认是**不可变(Immutable)**的,框架会冻结状态对象,禁止直接修改其属性值。原代码直接修改了DocumentList中对象的decisionDate属性,违反了不可变原则,因此触发只读属性报错。

解决方案(2023年7月3日更新)

遵循不可变更新原则,通过克隆对象、替换元素的方式修改状态:

  • 克隆需要修改的原始对象(使用扩展运算符...)
  • 修改克隆对象的目标属性
  • 用修改后的克隆对象替换原数组中的对应元素
  • 调用patchState更新状态

修正后的代码:

@Action(ClerkAction.Review.UpdateSelectedDate)  
onUpdateSelectedDate(ctx: StateContext<ClerkStateModel>, action: ClerkAction.Review.UpdateSelectedDate) {
    const DocumentList = ctx.getState().request.documents;
    const DocumentIndex = DocumentList.findIndex(item => item.guid === action.documentGuid);
    // 克隆要修改的对象
    const ItemToUpdate = {...DocumentList[DocumentIndex]};

    // 修改克隆对象的属性
    ItemToUpdate.decisionDate = action.newDate;

    // 用新对象替换原数组中的元素(假设addOrReplace是根据guid替换元素的工具函数)
    const updatedDocuments = addOrReplace('guid', DocumentList, ItemToUpdate);

    // 更新状态
    ctx.patchState({ 
        request: {
            ...ctx.getState().request,
            documents: updatedDocuments
        }        
    });

    ctx.dispatch(new NotificationAction.Loading(false));
}  

注:addOrReplace函数需实现根据guid在数组中查找并替换元素的逻辑,确保返回新的数组而非修改原数组。

内容的提问来源于stack exchange,提问作者Devon St. Denis - Richard

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 05:40:05