TypeScript将自定义类作为类属性时Express路由触发this指向错误
报错核心原因
这个报错的本质是类方法的this上下文绑定丢失,和你是否正确实例化PushController完全无关。
当你写routes.post('/xxx', pushController.getInstanceTokenInfo)时,只是把getInstanceTokenInfo这个函数的引用传递给了Express路由,后续Express收到请求调用这个函数时,会脱离pushController实例的上下文独立执行。
在TypeScript默认的严格编译模式下,独立调用的普通类方法内部的this值为undefined,执行到this.fcm这行时自然会抛出Cannot read property 'fcm' of undefined的运行时错误——此时的this根本不是你new出来的pushController实例,自然不存在fcm属性。
可落地的修正方案
你可以根据代码习惯选择任意一种修正方式:
- 方式一:传递路由回调时手动绑定this指向
用bind方法把方法内部的this永久绑定到pushController实例上,不需要改动原有类的代码:routes.post( '/push-token/instance/info', pushController.getInstanceTokenInfo.bind(pushController) ) - 方式二:把类方法改成箭头函数形式的类属性
箭头函数的this是词法绑定的,会自动绑定定义时的类实例上下文,传递到任意场景都不会丢失this指向,后续写路由时也不需要重复绑定:class PushController { public fcm: FCMServerSide = new FCMServerSide('myKey') // 替换原来的普通类方法写法 public getInstanceTokenInfo = async (request: Request, response: Response) => { try { const { token } = request.body console.log("==> Token Info: ", token) const apidata = await this.fcm.getInstanceTokenInfo(String(token)) if (token) { return response.json({ result: true, apidata }) } else { return response.json({ result: false, message: "No Token Provided" }) } } catch (e) { return response.json({ result: false, message: (e as Error).stack }) } } }
快速验证思路
如果你想快速定位问题,可以在new PushController()之后直接打印pushController.fcm,会发现这个属性是正常有值的,说明类的实例化、fcm属性的初始化逻辑没有问题,所有同类型的报错几乎都是this指向丢失导致的。
内容的提问来源于stack exchange,提问作者rdrgtec
相关产品推荐
相关产品推荐

