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

Express+TypeScript OOP开发:userService未定义类型错误排查

问题原因

你遇到的Cannot read properties of undefined (reading 'userService')错误,核心原因是类方法的this上下文丢失。当你把user.createNewUser直接作为路由处理函数传给app.post时,Express调用这个方法时不会绑定原类实例的this,导致方法内部的this变成了undefined,自然无法访问this.userService。

三种解决办法

1. 在构造函数中手动绑定this

修改UserController的构造函数,把类方法的this绑定到当前实例:

export class UserController {
  private userService: UserService;
  private jwtStrategy: JwtStrategy;

  constructor() {
    this.userService = new UserService();
    this.jwtStrategy = new JwtStrategy();
    // 手动绑定this到当前实例
    this.createNewUser = this.createNewUser.bind(this);
    this.authenticateUser = this.authenticateUser.bind(this);
  }

  // ... 其余代码不变
}

这样不管怎么传递createNewUser方法,它的this都会指向UserController的实例。

2. 使用箭头函数包裹路由处理函数

在路由文件里,用箭头函数包裹调用方法,确保this指向正确的实例:

// 路由文件修改部分
const user = new UserController()
app.post("/auth/local/signup", validate(createUserSchema), (req, res) => user.createNewUser(req, res))

箭头函数的this会继承外层作用域的上下文,这里外层的user是实例,所以调用时this会稳定指向它。

3. 把类方法定义为箭头函数

直接在类里用箭头函数定义方法,箭头函数的this会自动绑定到类实例:

export class UserController {
  private userService: UserService;
  private jwtStrategy: JwtStrategy;

  constructor() {
    this.userService = new UserService();
    this.jwtStrategy = new JwtStrategy();
  }

  // 改成箭头函数形式
  public createNewUser = async (
    req: Request<{}, {}, createUserInput["body"]>,
    res: Response
  ) => {
    try {
      const user = await this.userService.createNewUser(req.body);
      return res.status(CREATED).json(user);
    } catch (error) {
      log.error(error);
      return res.status(FORBIDDEN).send(error);
    }
  }

  // authenticateUser也可以改成同样的形式
  public authenticateUser = async () => {}
}

这种方式最简洁,不需要额外的绑定操作,适配TypeScript项目的写法习惯。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 15:00:15