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

使用InversifyJS注入依赖时出现Cannot read properties of undefined报错

问题原因

你遇到的报错和DI依赖注入流程没有关系,核心是类方法作为Express路由回调时丢失了this上下文。
你在路由文件中写router.get("/", pc.getProjects)时,相当于把ProjectController类原型上的getProjects函数单独摘出来传给了Express,函数执行时的this不再指向pc实例,自然读不到实例上的_processService属性,才会抛出Cannot read properties of undefined (reading '_processService')错误。
你可以在路由文件里const pc = myContainer.get(...)之后加一句console.log(pc),会发现_processService已经完成注入,容器绑定配置本身没有问题。

修复方案

选任意一种方式修改即可:

  • 方法1:注册路由时手动绑定this指向控制器实例
    修改routes/projects.ts的路由注册代码:
    router.get("/", pc.getProjects.bind(pc));
    
  • 方法2:用箭头函数包裹控制器方法调用,保留上下文
    router.get("/", (req, res) => pc.getProjects(req, res));
    
  • 方法3:在控制器类中将方法定义为箭头函数属性,永久绑定实例this
    修改controller/projects/projects.controller.ts里的方法定义:
    import { Request, Response } from "express";
    @injectable()
    class ProjectController {
      private _processService: IProjectService;
    
      constructor(@inject(TYPES.IProjectService) projectServicee: IProjectService) {
        this._processService = projectServicee;
      }
    
      // 箭头函数会绑定当前实例的this
      public getProjects = (req: Request, res: Response) => {
        const result = this._processService.getProject();
        res.send(result);
      };
    }
    
    export { ProjectController };
    
额外注意事项

你当前控制器的getProjects方法直接返回字符串,不符合Express路由处理函数的签名要求,路由处理函数必须接收req、res参数,通过res.send/ res.json等方法向客户端返回响应,否则接口请求会挂起超时。
另外确认tsconfig.json中已经开启装饰器相关配置(你当前已经能正常解析控制器实例,说明这部分配置已经正确,仅作提醒):

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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 19:03:41