Skip to content

Cannot assign 到 'X' 因为它 是读取-仅属性

错误信息

                Cannot assign 到读取-仅属性
              

快速摘要

你 tried 到 assign 新值 到属性 marked as readonly, or 到 Readonly<T> 对象. TypeScript prevents mutations 的 readonly 属性 at 编译时间.

为什么发生

  • Assigning 到属性 declared 使用 readonly

  • Mutating 对象输入 as Readonly<T>

  • Calling mutating 方法 on readonly 数组

  • Assigning 到属性的 const 对象 (shallow readonly)

最小示例

✗ 错误代码
interface Point { readonly x: number; y: number; }
const p: Point = { x: 10, y: 20 };
p.x = 30; // Error: x is readonly
✓ 修复代码
interface Point { readonly x: number; y: number; }
const p: Point = { x: 10, y: 20 };
const updated: Point = { ...p, y: 30 }; // create new object

创建新 对象使用更新值 相反的 mutating readonly 属性.

如何诊断

  • 检查如果属性 or 类型有 readonly modifier

  • 检查如果对象是 输入 as Readonly<T> or readonly T[]

  • Determine 如果 mutation 是必要 or 如果新 对象应该是 创建

如何修复

  • 创建新 对象使用更新值 (不可变更新)

  • 移除 readonly modifier 如果 mutation 是 intended

  • Use 非-readonly 复制: { ...obj, prop: newValue }

  • Cast 到可变类型如果你're 确定 mutation 是 safe

如何预防

  • Use 不可变更新模式使用 spread 语法

  • 是 intentional 关于哪个属性是 readonly

  • Use Readonly<T> consistently for 不可变数据 flows

相关资源

相关术语

← 返回语言