Angular与NgRx/store 17调度Action时出现undefined错误求助
解决NgRx 17调度Action时
TypeError: can't access property "type", creator is undefined错误 1. 检查Action的导入导出是否正确
- 确认
setTitleAction是通过export const正确导出的,没有拼写错误 - 查看Reducer里的导入路径,比如
import * as SharedActions from './shared.actions'是否正确,有没有路径写错或者循环导入的情况 - 可以在Reducer里加一行
console.log(SharedActions.setTitle),如果输出undefined,说明导入肯定有问题
2. 验证Feature模块的注册与跨模块依赖
- 如果是跨模块调用Action,要确保目标模块的
imports数组里导入了包含StoreModule.forFeature(fromShared.sharedFeature)的模块(比如你的SharedModule) - 检查
sharedFeatureKey是否正确定义并导出,比如export const sharedFeatureKey = 'shared',createFeature的name属性必须和StoreModule.forFeature使用的key一致
3. 排查NgRx 17的用法细节
- 确认
initialState的类型和结构正确,比如:export interface SharedState { title: string; } export const initialState: SharedState = { title: '' }; - 确保
on()函数的第一个参数是正经的Action creator,别传错了变量
4. 解决Tree-shaking导致的Action被误删
如果是生产环境才出现这个问题,大概率是Tree-shaking把Action creator移除了:
- 在使用Action的组件里显式引用一下(比如
console.log(setTitle)),防止被摇掉 - 检查
tsconfig.json的compilerOptions,确保preserveConstEnums等配置没有影响Action的保留
5. 确保Store注入和Action调度正确
在组件里调度Action时,直接导入具体的Action creator,别用间接引用:
import { Store } from '@ngrx/store'; import { setTitle } from './shared.actions'; constructor(private store: Store) {} updateTitle(newTitle: string) { this.store.dispatch(setTitle({ title: newTitle })); }
避免通过中间对象(比如SharedActions.setTitle)调用,如果导入路径有问题,很容易出现undefined
内容的提问来源于stack exchange,提问作者Federico Xella
相关产品推荐
相关产品推荐

