【问题标题】:Can't access deep nested object property without getting a readonly error在没有只读错误的情况下无法访问深层嵌套对象属性
【发布时间】:2019-09-14 15:08:24
【问题描述】:

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

错误类型错误:无法分配给对象“[object Object]”的只读属性“value”

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

@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';

我认为只有使用扩展运算符才能做到这一点,但这会将我的所有数组转换为对象,而我需要不惜一切代价保留我的数组。

这里是我尝试的传播解决方案:

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]
            }
          }
        }
      }
    }
  }
};

【问题讨论】:

  • 您尝试更改的属性似乎是defined 为只读的。所以我认为问题不是 嵌套,而是对象本身。

标签: javascript spread


【解决方案1】:

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

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

解决方案来自另一个帖子:https://stackoverflow.com/a/40922716/2664414

上面示例的问题是您只复制了根属性,而嵌套的子属性保持冻结状态。

由于我的值来自NGRX商店,所以基本处于“冻结”状态,无法调整。

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

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

【讨论】:

    【解决方案2】:

    也许您在某处将某些内容定义为constant,并且您正在尝试更改它。 Javascript 自然不支持只读道具,因此基本上在实践中,出现此错误的唯一原因是您将某些变量/道具定义为constant,或者您将obj的道具定义为writable=false,并且您正在尝试更改它.寻找 questionGroupIndexquestionGroupItemIndex 您可能正在尝试更改它们。无论哪种方式,问题都不在于嵌套。

    【讨论】:

    • 我追溯了一切,没有(更多)常量定义,questionGroupIndexquestionGroupItemIndex 也没有变化。我也尝试直接使用索引的值添加(...questionGroup[0]...)但没有结果。
    猜你喜欢
    • 2021-11-23
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 2020-12-15
    • 1970-01-01
    • 2014-07-09
    • 1970-01-01
    • 2020-11-21
    相关资源
    最近更新 更多