无法访问深层嵌套对象属性而不出现只读错误



每次我尝试访问深层属性(我通过索引猜测数组中的项目(时,都会收到以下错误:

错误

类型错误:无法将对象"[对象对象]"的只读属性"值"分配给只读

在下面找到我尝试运行的代码,但会抛出上面的错误:

@Input() data: CivilLiabilityQuestionnaireModel;
public questions: CivilLiabilityQuestionnaireModel;
this.questions = { ...this.data };
const questionGroupIndex = 0;
const questionGroupItemIndex = 0;
this.questions
    .questionGroup[questionGroupIndex]
    .questionGroupItems[questionGroupItemIndex]
    .answers[0]
    .value = form[val];
关于

可能的更多细节:

// This works
this.questions.id = 'hotdog';
// This doesn't work
// ERROR TypeError: Cannot assign to read only property 'id' of object '[object Object]'
this.questions.questionGroup[questionGroupIndex].id = 'hamburger';

我认为这只能通过使用 spread 运算符来实现,但这会将我所有的数组变成对象,而我需要不惜一切代价保留我的数组。

这是我尝试的点差解决方案:

this.questions = {
  ...this.questions,
  questionGroup: {
    ...this.questions.questionGroup,
    [questionGroupIndex]: {
      ...this.questions.questionGroup[questionGroupIndex],
      questionGroupItems: {
        ...this.questions.questionGroup[questionGroupIndex].questionGroupItems,
        [questionGroupItemIndex]: {
          ...this.questions.questionGroup[questionGroupIndex].questionGroupItems[questionGroupItemIndex],
          answers: {
            ...this.questions.questionGroup[questionGroupIndex].questionGroupItems[questionGroupItemIndex].answers,
            [0]: {
              ...this.questions.questionGroup[questionGroupIndex].questionGroupItems[questionGroupItemIndex].answers[0],
              value: form[val]
            }
          }
        }
      }
    }
  }
};

我设法找到了问题的解决方案。在原始问题的示例中,我执行以下操作:

this.questions = { ...this.data };

解决方案来自另一篇文章:https://stackoverflow.com/a/40922716/2664414

上面示例的问题在于,您只克隆根属性,而嵌套的子属性保持冻结状态。

由于我的价值来自NGRX商店,因此基本上处于"冻结"状态,无法调整。

要解决此问题,您可以使用 lodash 中的cloneDeep()来确保嵌套属性也被克隆并丢失"冻结"状态。

this.questions = _.cloneDeep(this.data);

也许你在某处将某些东西定义为constant,并且您正在尝试更改它。Javascript 本质上不支持只读 props,所以基本上在实践中,出现此错误的唯一原因是您要么将某个变量/prop 定义为 constant,要么将 obj 的 prop 定义为 writable=false 并尝试更改它。查找您可能尝试更改它们的questionGroupIndexquestionGroupItemIndex。无论哪种方式,问题都不在嵌套中。

相关内容

最新更新