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

TypeDi集成express时出现Cannot read property 'authService' of undefined如何解决

问题修复方案

首先明确报错的核心原因:不是AuthController注入失败,而是类方法作为路由回调传递时丢失了this指向。当Express调用你传入的getAuthUrl方法时,执行上下文不再绑定到AuthenticationController实例,导致this为undefined,自然无法读取authService属性。

可选修复方案(任选其一即可)

方案1:路由注册时用箭头函数包裹回调

修改AuthenticationRouter类的getRouter方法,包一层箭头函数保留上下文,这是侵入性最低的常用方案,不需要修改Controller代码:

getRouter () {
  const router = Router()
  // 用箭头函数继承外层this,保证controller实例指向正确
  router.get('/auth/url', (req, res) => this.authenticationController.getAuthUrl(req, res))
  return router
}

方案2:Controller中将方法定义为箭头函数

修改AuthenticationController的getAuthUrl为箭头函数形式,永久绑定this到实例:

@Service()
class AuthenticationController {
  constructor (private readonly authService: AuthenticationService) {}

  // 改为箭头函数,实例化时自动绑定this
  getAuthUrl = async (req: Request<{}, {}, {}, {redirect: string}>, res: Response) => {
    return res.redirect(this.authService.generateAuthenticationUrl(req.query.redirect))
  }
}

方案3:注册路由时用bind手动绑定上下文

在传递方法时用bind手动绑定controller实例:

getRouter () {
  const router = Router()
  router.get('/auth/url', this.authenticationController.getAuthUrl.bind(this.authenticationController))
  return router
}

补充确认项

如果修改后仍有问题,检查tsconfig.json中是否开启了以下配置,保证TypeDI注入逻辑正常生效:

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}

你现有代码的@Service()装饰器和依赖注入逻辑本身是正确的,不需要调整注入相关代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 11:54:01