NestJS调用注入Provider方法时出现Cannot read properties of undefined错误
问题排查:Cannot read properties of undefined (reading 'getSelfInfo')
这个错误的核心是AuthController实例中的service依赖未被正确注入,导致this.service为undefined,以下是常见的排查方向和解决办法:
1. TypeScript编译配置错误
NestJS依赖装饰器元数据和ES6+类特性实现依赖注入,若tsconfig.json配置不符合要求,会直接导致注入失效:
- 检查
tsconfig.json中的关键配置,确保以下项正确:
{ "compilerOptions": { "target": "ES2021", // 最低要求ES6,推荐ES2021及以上 "module": "commonjs", "experimentalDecorators": true, // 必须开启,Nest依赖装饰器实现注入 "emitDecoratorMetadata": true, // 必须开启,用于传递依赖注入的元数据 "baseUrl": "./", "paths": { "@/*": ["src/*"] // 匹配代码中使用的@/路径别名 } } }
- 若使用Nest CLI,确保
nest-cli.json指定了正确的配置文件路径:
{ "compilerOptions": { "deleteOutDir": true, "tsConfigPath": "tsconfig.json" } }
2. 旧编译产物干扰
dist目录的缓存代码可能导致异常,尝试清理后重新构建:
rm -rf dist && npm run build
3. 临时验证:修复this绑定
虽然代码写法本身合规,但编译后可能丢失this绑定,可临时将控制器方法改为箭头函数强制绑定this来验证:
@Controller('auth') export class AuthController { constructor (private readonly service: AuthService) {} @Get('me') public getSelfInfo = (): string => { return this.service.getSelfInfo() } }
注意:这只是临时验证手段,根源问题仍需通过修复编译配置解决。
4. 路径别名配置不完整
代码中使用了@/modules/...的路径别名,需确保:
tsconfig.json的paths配置正确映射到src目录- 若使用自定义构建工具(如Webpack),需同步配置路径别名(Nest CLI会自动读取tsconfig的paths,无需额外配置)
内容的提问来源于stack exchange,提问作者Dat Tran
相关产品推荐
相关产品推荐

