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

NestJS中onModuleInit调用ConfigService.get报undefined错误

问题分析与解决方案

这个问题并非OOP原则导致,核心原因是onModuleInit方法执行时this.configService的指向异常,以下是具体解决方法和排查点:

快速解决方案

将配置值提前在构造函数中获取,避免在onModuleInit中直接调用configService.get:

import { OnModuleInit } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as nodemailer from 'nodemailer';
import SMTPTransport from 'nodemailer/lib/smtp-transport';

interface EnvironmentVariables {
  MAIL_USER: string;
  MAIL_PASS: string;
}

export class MailService implements OnModuleInit {
  transporter: nodemailer.Transporter<SMTPTransport.SentMessageInfo>;
  private readonly mailUser: string;
  private readonly mailPass: string;

  constructor(private configService: ConfigService<EnvironmentVariables>) {
    // 构造函数中提前获取配置,确保值已初始化
    this.mailUser = configService.get('MAIL_USER', { infer: true });
    this.mailPass = configService.get('MAIL_PASS', { infer: true });
  }

  onModuleInit() {
    this.transporter = nodemailer.createTransport({
      host: 'smtp.office365.com',
      secure: false,
      tls: {
        ciphers: 'SSLv3',
      },
      auth: {
        user: this.mailUser,
        pass: this.mailPass,
      },
      logger: true,
      allowInternalNetworkInterfaces: false,
    });
  }
}

排查方向

  1. 检查服务注册方式
    确保MailService在模块中是通过useClass自动注册,而非手动实例化(手动实例化会导致ConfigService未注入):
@Module({
  providers: [MailService], // 正确:由Nest容器负责注入依赖
  // 错误示例:手动实例化未传入ConfigService
  // providers: [{ provide: MailService, useValue: new MailService() }]
})
export class YourModule {}
  1. 避免手动调用生命周期方法
    禁止在代码中手动调用onModuleInit,该方法由Nest容器在模块初始化时自动触发,手动调用会导致this上下文丢失。

  2. TypeScript编译选项检查
    确保tsconfig.json中开启了装饰器相关配置:

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 20:27:40