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

Redux Action未返回Payload数据问题求助

问题解决:Redux AsyncThunk Payload未传递到Reducer

你的问题核心在于createAsyncThunk的异步函数没有返回获取到的数据,导致fulfilled阶段的action.payload为undefined。

问题代码分析

在getUserProfile异步函数中,你虽然在axios的then回调里返回了response.data并赋值给res变量,但整个async函数没有将res作为返回值抛出。createAsyncThunk会把异步函数的返回值作为fulfilled action的payload,这里缺少了关键的返回步骤。

修改后的Action代码

export const getUserProfile = createAsyncThunk(
  "user/getuserprofile",
  async (thunkAPI) => {
    let user;
    const isAuthenticated = localStorage.getItem("isAuthenticated") === "true";
    if (isAuthenticated) {
      const access_token = localStorage.getItem("access_token");
      const decodedToken = jwt_decode(access_token);
      user = decodedToken.sub;
    }
    try {
      // 简化axios调用,直接用await获取响应
      const response = await axios.get(`${host}/manageAdmins/getUserProfile/${user}`);
      // 关键:返回数据作为payload传递给reducer
      return response.data;
    } catch (error) {
      return thunkAPI.rejectWithValue(error.response.data, { source: "API" });
    }
  }
);

额外优化建议

  • 去掉冗余的变量声明,让代码更简洁:
    try {
      const response = await axios.get(`${host}/manageAdmins/getUserProfile/${user}`);
      return response.data;
    } catch (error) {
      return thunkAPI.rejectWithValue(error.response.data, { source: "API" });
    }
    
  • 处理未认证场景:如果用户未登录,当前代码会发起/manageAdmins/getUserProfile/undefined的无效请求,建议提前拦截:
    if (!isAuthenticated) {
      return thunkAPI.rejectWithValue("用户未认证", { source: "Auth" });
    }
    

验证修改

修改后,请求成功时async函数返回的response.data会自动作为fulfilled action的payload传递给reducer,此时打印action.payload就能看到正确的数据。

内容的提问来源于stack exchange,提问作者Eyasu Emana

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 10:35:07