You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 10出现「Cannot set properties of undefined」错误是什么原因?

问题原因
  • 你的User类仅定义了docType的嵌套对象类型,没有在构造函数中初始化该属性,执行new User()生成实例后,u.docType的实际值为undefined。此时直接访问u.docType.documentTypeId等价于访问undefined的属性,会触发Cannot read properties of undefined类型的运行时错误。
修复方案

方案1:赋值前先初始化docType属性

在给嵌套属性赋值前,先给docType赋值一个符合类型要求的对象即可:

public insertUser(event: Event): void{
      event.preventDefault();
        
      const u: User = new User();

      u.id = this.form.value.id;
      u.name = this.form.value.name;
      u.nickname = this.form.value.nickname;
      u.password = this.form.value.password;
      // 新增初始化docType的代码
      u.docType = {
        documentTypeId: Number(this.form.value.typeId)
      };

      /*send to API, save to DB... */ 
}

方案2:给User类添加构造函数初始化逻辑

直接修改User类的定义,新增构造函数自动初始化docType,原有业务代码无需改动:

export class User{
    id: string;
    name: string;
    nickname: string;
    password: string;
    docType: {
        documentTypeId: number;
    }
    constructor() {
        // 初始化嵌套对象,设置默认值
        this.docType = {
            documentTypeId: 0
        }
    }
}

方案3:直接用对象字面量构造实例

如果你的User类仅用作数据结构、没有定义类方法,也可以直接用对象字面量生成符合类型要求的实例,省略手动逐个赋值的步骤:

const u: User = {
  id: this.form.value.id,
  name: this.form.value.name,
  nickname: this.form.value.nickname,
  password: this.form.value.password,
  docType: {
    documentTypeId: Number(this.form.value.typeId)
  }
}

内容的提问来源于stack exchange,提问作者Daniel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 10:15:05