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

如何将控制器类实例传入Fastify路由?构造函数未执行问题

问题原因及解决方案

问题本质

你遇到的核心问题是方法的this上下文丢失:当你直接把userController.login作为路由处理函数传给Fastify时,Fastify调用这个方法时,this并不会指向你从DI容器获取的userController实例,而是指向Fastify的请求上下文或其他对象,导致你误以为Fastify创建了新的类实例,构造函数里的初始化逻辑自然也无法生效。

三种解决方法

1. 用箭头函数包裹调用

把路由处理函数改成箭头函数,确保login方法始终绑定原实例的this:

async function adminRouter(server: FastifyInstance) {
  server.get('/', (req: Request, res: Response) => {
    res.sendFile('admin/index.html');
  });

  server.post('/user/login', { schema }, (req: Request, res: Response) => {
    return userController.login(req, res);
  });
}

2. 手动绑定this到实例

使用Function.bind()方法,把login方法的this强制绑定到userController实例:

async function adminRouter(server: FastifyInstance) {
  server.get('/', (req: Request, res: Response) => {
    res.sendFile('admin/index.html');
  });

  server.post('/user/login', { schema }, userController.login.bind(userController));
}

3. 在类内部定义箭头函数方法

如果有权修改UserController类,可以把login定义成类属性箭头函数,这样this会自动绑定到类实例:

class UserController {
  constructor() {
    // 你的构造函数初始化逻辑
  }

  // 用箭头函数定义方法,自动绑定this
  login = (req: Request, res: Response) => {
    // login方法业务逻辑
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 14:39:52