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

使用InversifyJS时出现Cannot read properties of undefined错误求助

问题解决:InversifyJS中this上下文丢失导致的错误

错误原因

你遇到的TypeError: Cannot read properties of undefined (reading '_userService'),核心原因是将UserController的getAll方法作为回调传递给路由时,方法的this上下文丢失。此时this不再指向UserController的实例,导致_userService无法被访问。

解决方案

你不需要额外实现"get"方法,只需要修复this的绑定问题,以下是三种可行方案:

方案1:在路由中直接绑定上下文

修改user.routes.ts中的路由定义,通过bind()将getAll方法绑定到_controller实例:

// user.routes.ts
public routes(router: express.Router): express.Router {
    router
        .route('/users')
        .get(mw.isAllowed([SUPERADMIN]), catchErrors(this._controller.getAll.bind(this._controller)));

    return router;
}

方案2:用箭头函数定义控制器方法

箭头函数会自动继承当前类的this上下文,修改user.controller.ts中的getAll方法:

// user.controller.ts
@injectable()
export class UserController {
    private _userService: UserService;

    constructor(@inject(UserService) private readonly userService: UserService) {
        this._userService = this.userService;
    }

    public getAll = async (req: Request, res: Response): Promise<User[]> => {
        return this._userService.getAll();
    }
}

方案3:在路由类构造函数中提前绑定

在UserRouter的构造函数里,提前将getAll方法绑定到控制器实例:

// user.routes.ts
@injectable()
export class UserRouter {
    private _controller: UserController;

    public constructor(@inject(UserController) private readonly controller: UserController) {
        this._controller = controller;
        // 提前绑定上下文
        this._controller.getAll = this._controller.getAll.bind(this._controller);
    }

    public routes(router: express.Router): express.Router {
        router
            .route('/users')
            .get(mw.isAllowed([SUPERADMIN]), catchErrors(this._controller.getAll));

        return router;
    }
}

额外检查

你的InversifyJS依赖绑定逻辑没有问题,所有类都正确添加了@injectable()装饰器,依赖也已正确注入,只需修复this绑定即可解决问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 13:07:50