React Redux - 不变失败:在调度内检测到状态突变

我收到此错误:Invariant failed: A state mutation was detected inside a dispatch并且似乎无法找到解决方案。我通过 API 获取用户支持票证并将其保存到某个状态以显示票证信息。这是我的代码:

const initialState: stateType = {

    User: new User(),

    SupportTickets: new SupportTickets()

}


const userSlice = createSlice({

    name: "User",

    initialState,

    reducers: {

        setUser: (state, {payload}) => {

            state.User = payload

        },

        setSupportTickets: (state, {payload}) => {

            state.SupportTickets.tickets = payload

        }

    }

})


export const {setUser, setSupportTickets} = userSlice.actions


export const userSelector = (state: stateType) => state.User

export const userSupportTicketsSelector = (state: stateType) => state.SupportTickets


export function fetchSupportTickets(userId: string, token: string) {

    return async (dispatch: AppDispatch) => {

        return await fetch(API_URL, {

            method: 'GET',

            headers: {

                Authorization: `Bearer ${token}`

            }

        }).then(response => {

            if (!response.ok) { throw response }

            return response.json()

        }).then(json => {

            dispatch(setSupportTickets(json))

        }).catch(error => {

            console.log('Failed to fetch support tickets', error);

        })

    }

}


interface stateType {

    User: User

    SupportTickets: SupportTickets

}

export class SupportTickets {

    tickets: SupportTicket[] = []

}


export class SupportTicket {

    id: number = 0

    type: string = ""

    subject: string = ""

    priority: string = ""

    status: string = ""

    created_at: string = ""

    updated_at: string = ""

}

我尝试过改变/移动事物但没有成功。任何帮助是极大的赞赏。提前致谢。


慕容森
浏览 301回答 1
1回答

弑天下

我看到了问题所在。看起来您正在创建某种类来存储数据,并将它们置于 Redux 状态:const initialState: stateType = {    User: new User(),    SupportTickets: new SupportTickets()}您永远不应该将类实例或其他不可序列化的值放入 Redux 状态。相反,您应该使用纯 JS 对象、数组和基元。好消息是您正在使用 Redux Toolkit 的createSliceAPI,它可以让您编写“变异”更新逻辑,从而成为安全且正确的不可变更新。但是,您需要在我们的状态中使用纯 JS 对象才能正常工作。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript