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

NestJS依赖注入异常:未使用@Inject()则依赖未定义

NestJS依赖注入报错排查

问题现象

调用接口时抛出错误:

TypeError: Cannot read properties of undefined (reading 'foo')

相关代码

报错的控制器代码:

import { Controller, Get } from '@nestjs/common'
import { TestService } from './TestService.service'

@Controller()
export class TestController {
  constructor(private testService: TestService) {}

  @Get('join')
  join() {
    this.service.foo()
    return 'success'
  }
}

服务代码:

import { Injectable } from '@nestjs/common'

@Injectable()
export class TestService {
  foo() {
    console.log('foo')
  }
}

AppModule代码:

@Module({
  providers: [TestService],
  controllers: [TestController],
})
export class AppModule {}

尝试在构造函数参数上添加@Inject(TestService)注解后,接口调用成功,误以为是构造函数注入失效。

问题根源

核心错误是变量名拼写错误:构造函数中注入的属性是testService,但join方法里调用的是this.service——this.service从未被定义,因此抛出undefined错误。

添加@Inject注解后“成功”,大概率是修改代码时同时修正了变量名(比如改成this.testService.foo()),只是未留意。@Inject注解在这个场景下完全多余,NestJS默认支持基于类型的构造函数注入,不需要额外添加。

修正方案

直接修正方法中的变量调用即可,无需添加@Inject:

import { Controller, Get } from '@nestjs/common'
import { TestService } from './TestService.service'

@Controller()
export class TestController {
  constructor(private testService: TestService) {}

  @Get('join')
  join() {
    this.testService.foo() // 修正为正确的属性名
    return 'success'
  }
}

补充说明

你的NestJS版本(@nestjs/common@^10.3.8、@nestjs/core@^10.3.7等)完全支持基于类型的构造函数注入,只有以下场景才需要显式使用@Inject:

  • 使用自定义字符串/符号作为注入token
  • 注入非类类型的提供者(值提供者、工厂提供者等)
  • 处理循环依赖等特殊情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 12:22:37