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

Express接口请求触发TypeError: Cannot read properties of undefined问题求助

TypeError: Cannot read properties of undefined (reading 'service') 解决方案

问题根源

把controller.getAll作为Express路由处理函数时,Express调用该函数不会绑定controller实例的上下文,导致函数内部的this指向undefined(严格模式下),因此访问this.service会触发报错。而直接调用controller.getAll()时,this会自动绑定到controller实例,所以能正常运行。

三种可行修复方案

方案1:箭头函数包裹路由回调

在index.ts注册路由时,用箭头函数包裹处理逻辑,强制绑定controller实例的上下文:

app.get('/api/all', (req, res) => controller.getAll(req, res));

方案2:controller类方法改用箭头函数

修改controller.ts中的getAll方法为箭头函数,让方法自动捕获类实例的上下文:

class Controller {
  private service: Service;

  constructor() {
    this.service = new Service();
  }

  getAll = (req: Request, res: Response) => {
    const data = this.service.findAll();
    res.json(data);
  }
}

方案3:手动绑定this到controller实例

在index.ts注册路由时,通过bind方法把controller实例绑定到getAll函数:

app.get('/api/all', controller.getAll.bind(controller));

方案优缺点对比

  • 方案1:无需改动controller代码,实现简单,适合小项目或临时修复。
  • 方案2:一劳永逸,后续新增方法无需再关注上下文问题,但会增加类实例的内存开销(每个实例会生成独立的方法副本)。
  • 方案3:保持方法的原型链特性,不额外占用内存,但需要手动绑定每个路由方法,容易遗漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 22:29:56