TypeScript更新类实例对象变量报错:属性为只读问题求助
解决TypeScript类实例属性无法修改的只读错误
错误原因
你遇到的运行时错误核心原因是:传入类构造函数的原始data对象处于只读/冻结状态(比如被Object.freeze()处理过,或是来自不可修改的上下文如React props)。此时:
- 直接修改
this.data.x_value会触发报错,因为你在操作原始只读对象的属性 - 若修改
this.x_value也报错,大概率是实际场景中Object.assign(this, data)未正确复制原始值(比如原始对象的属性是访问器而非基础值),或是实例属性意外绑定到了只读对象的引用上
解决方案
方案1:构造函数内创建data副本
在构造函数中不直接保存原始data的引用,而是创建一个可修改的浅拷贝,彻底脱离原始只读对象的限制:
export interface theInterface { x_value: number; y_value: number; }; export class theClass implements theInterface { public x_value: number; public y_value: number; public data: theInterface; constructor(data: theInterface) { // 创建原始data的可修改副本 this.data = {...data}; // 将副本属性同步到实例自身 Object.assign(this, this.data); } public setValues(incoming_data: theInterface) { this.data.x_value = incoming_data.x_value; this.data.y_value = incoming_data.y_value; this.x_value = incoming_data.x_value; this.y_value = incoming_data.y_value; } }
方案2:移除冗余data属性(简化版)
既然已经通过Object.assign将data的属性复制到实例本身,完全可以去掉额外的data引用,直接操作实例自身属性:
export interface theInterface { x_value: number; y_value: number; }; export class theClass implements theInterface { public x_value: number; public y_value: number; constructor(data: theInterface) { Object.assign(this, data); } public setValues(incoming_data: theInterface) { this.x_value = incoming_data.x_value; this.y_value = incoming_data.y_value; } }
验证测试
使用修改后的代码执行,即可正常更新属性且无报错:
let thing = new theClass({ x_value: 10, y_value: 20 }); thing.setValues({ x_value: 22, y_value: 55 }); console.log(thing.x_value); // 输出22
内容的提问来源于stack exchange,提问作者dadelsvesken
相关产品推荐
相关产品推荐

