问题描述
我正在尝试使用immer创建异步产品,但是在调用此异步函数时出现错误:
这是我的代码:
import { combineReducers,createStore } from 'redux';
import produce from 'immer';
const mainReducer = produce(async (draft,{ type,payload }: { type: string; payload: any }) => {
switch (type) {
case 'foo': {
draft = await myAsyncFn(payload);
}
}
});
const reducers = {
main: mainReducer,};
const rootReducer = combineReducers(reducers);
export const mainStore = createStore(rootReducer);
这是输出:Error: [Immer] produce can only be called on things that are draftable: plain objects,arrays,Map,Set or classes that are marked with '[immerable]: true'. Got '[object Promise]'
为什么不起作用? (我以为有可能:https://immerjs.github.io/immer/docs/async)
classes that are marked with '[immerable]
是什么意思?
解决方法
虽然Immer确实可以让您在produce
,you must never write async logic in a Redux reducer内编写异步逻辑。
话虽如此,这里的特定错误是因为默认情况下,Immer只知道如何更新普通的JS对象和数组。为了更新类实例或类似的实例,请you have to add a special immerable
symbol to that class type。
请注意,您应该将Immer与Redux一起使用,但是as part of our official Redux Toolkit package,其createSlice
API中内置了Immer。