首页 > 解决方案 > TypeError:“属性”是只读的

问题描述

我将角度从 8 更新到 12,并且在项目的许多地方,控制台中出现错误:TypeError:“property_name”是只读的。

这是一个有错误的对象的示例:

export interface ObjectName {
    index: number;
    name: string;
    widgets: ArrayType[];
}

这是发生错误的代码:

ngOnChanges(): void {
        this.Areas = this.areas
        .map(area => {
            area.index = 10; // ERROR "index" is read-only
            switch (area.name) {
                case '1': area.index = 0; break;
                case '2': area.index = 1; break;
                case '3': area.index = 2; break;
            }

            return area;
        })
        .sort((a, b) => (a.index - b.index));
    }

而且现在项目中有很多这样的地方,我不明白如何修复它。我尝试将接口更改为一个类,但一切都是一样的。这是我的 tsconfig.json,但我阅读了它的各种设置,似乎没有什么可以帮助我。

{
    "compileOnSave": false,
    "compilerOptions": {
        "baseUrl": "./",
        "downlevelIteration": true,
        "outDir": "./dist/out-tsc",
        "sourceMap": true,
        "declaration": false,
        "module": "es2020",
        "emitDecoratorMetadata": true,
        "moduleResolution": "node",
        "experimentalDecorators": true,
        "importHelpers": true,
        "target": "es5",
        "typeRoots": ["node_modules/@types"],
        "lib": ["es2018", "dom"]
    }
}

错误截图

标签: javascriptangulartypescriptruntime-errortypeerror

解决方案


您将需要返回一个新对象(重新分配)。像这样的东西会起作用:

.map(area => {
    let index = 10;
    switch (area.name) {
        case 'header_area': index = 0; break;
        case 'content_area': index = 1; break;
        case 'footer_area': index = 2; break;
    }

    return {...area, index};
})

扩展运算符...会将 的内容分配给area新对象并index用新值覆盖。Extra:index: index是多余的,但是如果局部变量具有不同的名称,则需要执行 eg index: newIndex


推荐阅读