Nx Angular项目启动报错:TypeError: Cannot read properties of undefined (reading '0')
问题背景
在Nx Angular项目中引入自定义库MyModule,已在AppModule的imports中导入该模块,同时配置了StoreModule.forRoot()和EffectsModule.forRoot(),但启动应用时抛出类型错误,该库在其他项目中可正常运行,复现实现方式未成功。
AppModule.ts 代码
@NgModule({ declarations: [AppComponent], imports: [ StoreModule.forRoot(), EffectsModule.forRoot(), MyModule.forRoot(), ... ], })
报错信息
main.ts:14 TypeError: Cannot read properties of undefined (reading '0')
Main.ts 第14行代码
platformBrowserDynamic().bootstrapModule(AppModule);
完整报错栈
main.ts:14 TypeError: Cannot read properties of undefined (reading '0')
at ngrx-store.mjs:1341:51
at Array.map ()
at Object.featureStateProviderFactory [as useFactory] (ngrx-store.mjs:1338:28)
at Object.factory (core.mjs:3322:38)
at core.mjs:3219:47
at runInInjectorProfilerContext (core.mjs:866:9)
at R3Injector.hydrate (core.mjs:3218:21)
at R3Injector.get (core.mjs:3082:33)
at injectInjectorOnly (core.mjs:1100:40)
at ɵɵinject (core.mjs:1106:60)
报错细节(ngrx-store.mjs:1338:28)
错误发生在const reducers = featureReducerCollection[index]行:
function featureStateProviderFactory() { inject(ROOT_STORE_PROVIDER); const features = inject(_STORE_FEATURES); const featureReducers = inject(FEATURE_REDUCERS); const reducerManager = inject(ReducerManager); inject(_ACTION_TYPE_UNIQUENESS_CHECK, { optional: true }); const feats = features.map((feature, index) => { const featureReducerCollection = featureReducers.shift(); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const reducers = featureReducerCollection /*TODO(#823)*/[index]; return { ...feature, reducers, initialState: _initialStateFactory(feature.initialState), }; }); reducerManager.addFeatures(feats); }
MyModule.ts 代码
export class MyModule { public static forRoot(): ModuleWithProviders<MyModule> { return { ngModule: MyModule, providers: [ { provide: SOME_CONFIG, useFactory: getEnvironment, deps: [AA_ENVIRONMENT, BB_ENVIRONMENT], }, { provide: LOCALE_ID, useValue: 'fr', }, SomeRepository, SomeService, OtherRepository, OtherService, ], }; } }
问题分析
从报错栈和NGRX源码来看,featureReducerCollection为undefined,说明featureReducers.shift()取出的是undefined,即FEATURE_REDUCERS注入令牌对应的集合中没有足够元素匹配_STORE_FEATURES的数量。
核心诱因:
StoreModule.forRoot()无参数调用,导致NGRX内部未正确初始化feature reducer集合,无法匹配自定义库中可能存在的NGRX feature模块。- 自定义库
MyModule内部可能使用了StoreModule.forFeature(),但主应用NGRX初始化方式不兼容,或版本与库依赖的NGRX版本不一致。
解决方案
修正
StoreModule.forRoot()调用
即使没有根reducers,也需传入空对象确保NGRX内部初始化流程正常:StoreModule.forRoot({}), // 传入空对象而非无参数对齐NGRX版本
检查自定义库MyModule依赖的NGRX版本,确保与主应用的NGRX版本完全一致,避免因版本差异导致注入令牌不兼容。调整模块导入顺序
确保NGRX核心模块先完成初始化,再导入自定义库:imports: [ StoreModule.forRoot({}), EffectsModule.forRoot(), MyModule.forRoot(), ... ],验证依赖注入完整性
确认主应用中已正确提供AA_ENVIRONMENT和BB_ENVIRONMENT,避免因依赖缺失导致模块初始化异常,间接干扰NGRX流程。
内容的提问来源于stack exchange,提问作者Ryley38

