我收到此错误: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.actionsexport const userSelector = (state: stateType) => state.Userexport const userSupportTicketsSelector = (state: stateType) => state.SupportTicketsexport 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 = ""}我尝试过改变/移动事物但没有成功。任何帮助是极大的赞赏。提前致谢。
1 回答
弑天下
TA贡献1818条经验 获得超8个赞
我看到了问题所在。看起来您正在创建某种类来存储数据,并将它们置于 Redux 状态:
const initialState: stateType = {
User: new User(),
SupportTickets: new SupportTickets()
}
您永远不应该将类实例或其他不可序列化的值放入 Redux 状态。相反,您应该使用纯 JS 对象、数组和基元。
好消息是您正在使用 Redux Toolkit 的createSlice
API,它可以让您编写“变异”更新逻辑,从而成为安全且正确的不可变更新。但是,您需要在我们的状态中使用纯 JS 对象才能正常工作。
添加回答
举报
0/150
提交
取消