【问题标题】:"Unexpected key "foo" found in previous state received by the reducer" with redux-toolkit configure store and a custom store enhancer使用 redux-toolkit 配置存储和自定义存储增强器“在减速器收到的先前状态中发现意外的键“foo””
【发布时间】:2025-12-03 01:30:02
【问题描述】:

我一直在尝试创建一个商店增强器,为我的根状态添加一些新值。然而,在我了解了自定义增强器的所有工作原理之后,我遇到了一个意外的关键错误。我可以在 devtools 中看到状态的新部分,并且应用程序似乎工作正常,但是我得到了

Unexpected key "foo" found in previous state received by the reducer. 
Expected to find one of the known reducer keys instead: [...]. Unexpected keys will be ignored.

我根本不明白。我试着四处搜索,但我找到的帖子都没有关于自定义商店增强器的案例。

这是重现上述错误的最少代码。我正在这样创建我的商店:

export const store = configureStore({
    reducer: mainReducer,
    enhancers: [testEnhancer],
});

其中 mainReducer 只是 combineReducers({ "my slices" }) 并且所有切片都是使用 RTK 中的 createSlice 创建的。

testEnhancer 如下所示:

type StateExt = { foo: string }
export const testEnhancer: StoreEnhancer<{}, StateExt> = (next: StoreEnhancerStoreCreator): StoreEnhancerStoreCreator<{}, StateExt> => {
    
    return <S, A extends Action = AnyAction>(reducer: Reducer<S, A>, preloadedState?: PreloadedState<S>): Store<S & StateExt, A> => {
        
        const wrappedReducer: Reducer<S & StateExt, A> = (state, action) => {
            return { ...reducer(state, action), foo: 'bar' };
        };
        
        return next(wrappedReducer, { ...preloadedState, foo: '' });
    };
};

【问题讨论】:

    标签: javascript typescript redux redux-toolkit


    【解决方案1】:

    这实际上是combineReducers 特有的行为。它期望任何*状态键和相关的切片缩减器之间永久 1:1 映射。

    您需要以某种方式设置自定义减速器来处理此问题,或者使用combineReducers。 (那里有许多类似的版本,它们的整体行为相同,但也减去了警告。)

    【讨论】:

      最近更新 更多