React+Express项目中调用类方法出现TypeError: Cannot read property 'createFromSystem' of undefined的解决求助
解决TypeError: Cannot read property 'createFromSystem' of undefined问题
这个错误的核心原因是**getOne方法的this上下文丢失了**。当你把this.getOne作为参数传给asyncWrapper时,它脱离了类的实例上下文,导致在getOne内部调用this.createFromSystem时,this变成了undefined(严格模式下)。
你已经知道要绑定createFromSystem的上下文,但同样的处理也需要用到getOne上。下面是几种可行的解决方法:
方法1:在构造函数中绑定getOne
在控制器的构造函数里,添加对getOne的绑定,就像你处理createFromSystem一样:
constructor() { this.initializeRoutes(); this.createFromSystem = this.createFromSystem.bind(this); this.getOne = this.getOne.bind(this); // 新增这行绑定 }
方法2:在路由中使用箭头函数包裹
修改initializeRoutes里的路由注册逻辑,用箭头函数来保留类实例的上下文:
private initializeRoutes() { this.router.get( `${this.path}/getOne/:evaluationId/:targetWordId`, asyncWrapper(authenticationMiddleware), asyncWrapper((req, res) => this.getOne(req, res)) // 用箭头函数包裹getOne调用 ); }
方法3:使用类字段的箭头函数语法(推荐)
把getOne和createFromSystem改成箭头函数形式,这样它们会自动绑定类实例的this,不需要手动执行绑定操作:
private getOne = async (request: AuthenticatedRequest<any>, response: Response) => { // 原getOne方法的代码逻辑 } private createFromSystem = async (evaluationId: string, targetWordId: string): Promise<PhoneticInventory> => { // 原createFromSystem方法的代码逻辑 }
这种方式更简洁,也避免了手动绑定的繁琐,是TypeScript中处理类方法上下文的常用方案。
另外提醒一下:你在createFromSystem里定义phoneticInventory对象时,plosiva、fricativa等变量都没有初始化赋值,这会导致新的报错,记得补充这些变量的生成逻辑哦。
内容的提问来源于stack exchange,提问作者João Bolsson
相关产品推荐
相关产品推荐

