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

createAsyncThunk返回action.payload为Undefined问题排查

问题原因

action.payload为undefined的核心原因是fileFetch函数没有将接口返回的数据作为自身返回值返回:

  • 你在fileFetch中仅对api.get()的Promise调用了await,但没有将Promise的执行结果return出去
  • 你在.then()回调里写的return res.data只是回调函数的返回值,会作为await的计算结果,但因为你没有在await前加return,整个fileFetch异步函数执行完成后默认返回undefined
  • createAsyncThunk会拿到fileFetch()的返回值作为fulfilled状态的payload,拿到undefined就会导致action.payload为undefined

另外你的代码里还有一个隐藏bug:initialState中loading的赋值写法错误。你写的"idle" | "pending" | "succeeded" | "failed"在JavaScript中是按位或运算,不是类型定义,运行后会得到0作为loading初始值,不是预期的"idle"。

修复方案
  1. 修正fileFetch函数,将接口请求结果返回,推荐直接用async/await搭配try/catch的写法,避免和Promise链式调用混用产生返回值问题:
export const fileFetch = async () => {
  try {
    const res = await api.get("getAll");
    console.log(res.data);
    return res.data;
  } catch (err) {
    throw new Error(err);
  }
};

如果你要保留原来的.then()写法,只需要在await前加return即可:

export const fileFetch = async () => {
  // 新增return,将Promise链的结果作为函数返回值
  return await api
    .get("getAll")
    .then((res) => {
      console.log(res.data);
      return res.data;
    })
    .catch((err) => {
      throw new Error(err);
    });
};
  1. 修正initialState中loading的初始值,不要把TS类型定义直接写在JS对象的赋值里:
const initialState = {
  loading: "idle",
  error: false,
  filesUploaded: null,
};

内容的提问来源于stack exchange,提问作者Alvaro Augusto Fernandes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 03:27:30