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

TypeScript类设置属性时报TypeError: Cannot set property错误怎么解决?

报错原因

该报错的核心是类被作为普通函数直接调用,未使用new关键字导致this指向丢失:

  • ES6/TypeScript的class语法是构造函数的语法糖,默认开启严格模式,直接调用类函数时this不会指向全局对象,而是被赋值为undefined,因此给this.type_赋值时会触发“Cannot set property of undefined”错误。
  • 你提供的调用代码直接写了Component("Section"),缺少new关键字,和TS类代码本身的写法无关。
解决方案

方案1:补全new关键字(推荐)

符合类的常规使用规范,修改调用代码即可:

const base = require('./lib/components/base');
const { Component } = base;
// 新增new关键字实例化类
const componentInstance = new Component("Section");
// 可正常调用类方法
console.log(componentInstance.getDefinition())

方案2:改造TS类兼容无new调用(特殊场景使用)

如果业务确实需要支持不用new直接调用的场景,可以在类构造函数中增加判断逻辑,主动处理无new调用的情况:

class Component {
    type_: string;

    constructor(type_: string) {
        // 检测到无new调用时主动返回实例
        if(!new.target) return new Component(type_)
        this.type_ = type_;
    }

    getDefinition(): Object {
        return {
            type: this.type_
        };
    };
}

export { Component };

改造后原来的Component("Section")写法也可以正常返回实例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 04:57:02