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

从Angular/NgRx 13升级到15后出现Null Injector Error的解决方法

Angular 15 + NgRx 15 升级后 StoreModule.forRoot 空注入器错误解决办法
  • 检查NgRx依赖版本一致性
    确保所有NgRx相关包(@ngrx/store、@ngrx/effects、@ngrx/entity等)版本统一为15.2.1,与Angular 15.2.2兼容。执行npm list @ngrx/*查看各包版本,若存在不一致,重新安装指定版本:

    npm install @ngrx/store@15.2.1 @ngrx/effects@15.2.1 @ngrx/entity@15.2.1 @ngrx/router-store@15.2.1
    
  • 确认StoreModule.forRoot的配置正确性
    Angular 14+后,NgRx的StoreModule.forRoot无需额外提供StoreRootModule,检查根模块(AppModule)的导入写法:

    import { StoreModule } from '@ngrx/store';
    import { reducers, metaReducers } from './reducers';
    
    @NgModule({
      imports: [
        // 正确配置方式
        StoreModule.forRoot(reducers, { metaReducers })
      ]
    })
    export class AppModule { }
    

    注意:仅根模块可使用StoreModule.forRoot,功能模块需用StoreModule.forFeature注册特性reducer,避免重复导入引发冲突。

  • 调整模块导入顺序
    确保StoreModule.forRoot在所有依赖NgRx的模块(如EffectsModule.forRoot)之前导入,根模块的imports数组中,StoreModule需排在EffectsModule、RouterModule等依赖它的模块前面,保证注入时机正确。

  • 清理缓存并重建项目
    删除node_modules和锁文件,重新安装依赖后构建项目:

    # Linux/Mac
    rm -rf node_modules package-lock.json
    npm install
    ng serve
    
    # Windows
    rmdir /s /q node_modules
    del package-lock.json
    npm install
    ng serve
    
  • 排查懒加载模块冲突
    检查所有懒加载模块,确认未错误导入StoreModule.forRoot,仅能使用StoreModule.forFeature。同时验证懒加载模块内的NgRx服务是否正确提供,避免重复注入导致的依赖混乱。

  • 验证Angular编译器配置
    查看tsconfig.json中的compilerOptions,若开启strictNullChecks等严格模式选项,可暂时关闭后测试是否解决问题,部分旧代码可能在严格模式下引发注入异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 22:03:10