首页 > 解决方案 > “x”是只读的,但不是

问题描述

我有一个具有以下类的 Angular 10 (Typescript 3.9) 项目:

export class Document {
    constructor(
        public id: number,
        ...
        public tags: Tag[]
    ) {
        this.id = id;
        ...
        this.tags = tags;
    }
}

如果我尝试更改标签(重新分配或推送)

文档标签 = ...

例如在现有对象中,我得到:

错误类型错误:“标签”是只读的

如果我有一个

只读

我会期待这种行为。你知道这个错误来自哪里吗?

我最近从 Angular 7 升级到 10,在此之前一切正常,但升级说明没有提到这种行为。

停用严格模式(即使被认为是不好的做法)不起作用。

你有什么主意吗?

标签: angulartypescriptngrx

解决方案


这是根据评论的答案。

更改 ngrx 存储的对象可能会导致这种行为,因为存储会从 reducer 外部保护要更改的对象。

大多数人额外安装了 Pre Angular 8ngrx-store-freeze以恢复安全性。在 Angular 8 中,该功能已内置。

您可以尝试通过设置为 来禁用它strictStateImmutabilityfalse但不建议这样做,因为存储现在可以包含不可预知的更改。

@NgModule({
  imports: [
    StoreModule.forRoot(reducers, {
      runtimeChecks: {
        strictStateImmutability: false,
      },
    }),
  ],
})
export class AppModule {}

推荐阅读