You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Redux开发影评应用时为何出现「状态存在不可序列化值」警告?

问题原因及解决方法

问题出在你的fetchmovie reducer标记了async关键字——Redux的reducer必须是同步纯函数,async函数会返回Promise对象,而Promise属于非序列化值,Redux检测到后就会抛出「A non-serializable value is detected in the state」警告。

解决步骤

  1. 移除reducer中的异步逻辑,改用Redux Toolkit提供的createAsyncThunk来处理异步请求
  2. 通过extraReducers处理异步请求的不同状态(pending/fulfilled/rejected)

修改后的代码示例:

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';

// 封装异步获取电影的逻辑
export const fetchmovie = createAsyncThunk(
  'movie/fetchmovie',
  async (payload) => {
    console.log(payload);
    // 这里添加你的axios请求逻辑,示例:
    // const res = await axios.get(`/api/movies/${payload}`);
    // return res.data;
  }
);

const initialState = {};

const MovieSlice = createSlice({
  name: 'movie',
  initialState,
  reducers: {
    addmovie: (state) => {
      // 这里写addmovie的同步逻辑
    }
  },
  // 处理异步请求的状态更新
  extraReducers: (builder) => {
    builder
      .addCase(fetchmovie.pending, (state) => {
        // 可选:设置加载状态,比如 state.loading = true
      })
      .addCase(fetchmovie.fulfilled, (state, action) => {
        // 请求成功后,把数据存入state,比如 state.movies = action.payload
      })
      .addCase(fetchmovie.rejected, (state) => {
        // 可选:处理请求失败,比如 state.error = true
      });
  }
});

export const { addmovie } = MovieSlice.actions;
export default MovieSlice.reducer;

关键说明

  • createAsyncThunk会自动生成对应异步流程的action,避免在reducer中直接写异步逻辑
  • extraReducers用于响应这些异步action,更新state的操作仍然是同步的,符合Redux的规则

内容的提问来源于stack exchange,提问作者ashutosh singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 23:07:07