Immer-在生产中使用异步功能获取错误

问题描述

我正在尝试使用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确实可以让您在produceyou 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。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...