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

Redux-Toolkit中createAsyncThunk解构cart参数出现undefined问题

问题解决:createAsyncThunk中解构cart得到undefined

你遇到的问题核心在于:createAsyncThunk的第二个参数是thunkAPI对象,这个对象本身并不包含cart属性,所以直接解构{ cart }自然会得到undefined。

正确的做法是通过thunkAPI提供的getState()方法获取当前Redux Store的完整状态,再从状态中提取cart数据。另外需要注意,Redux要求状态不可变,不能直接调用cart.push(item)修改原数组,必须返回新的数组对象。

修改后的代码示例:

export const addToBasket = createAsyncThunk(
  "newBasket/addToBasket",
  async (id, { getState }) => {
    const res = await axios.get("https://run.mocky.io/v3/04fe3f95-0267-4ab4-a61b-a5f250151459");
    const data = res.data;
    // 根据你的Store结构,从state中获取当前cart(路径需自行调整)
    const currentCart = getState().newBasket.cart;
    // 查找匹配ID的商品
    const matchedItem = data.find(item => item.id === id);
    
    if (matchedItem) {
      // 返回新数组,遵循Redux不可变更新原则
      return [...currentCart, matchedItem];
    }
    // 未找到匹配商品时返回原cart
    return currentCart;
  }
);

补充说明:

  • getState()返回的是整个Store的状态对象,你需要根据自己定义的slice名称和状态结构,调整访问cart的路径(比如getState().yourSliceName.cart)
  • 用find替代map更高效,因为找到匹配项后会立即停止遍历
  • 改用async/await语法比链式then更简洁易读

内容的提问来源于stack exchange,提问作者Hasan Sherafat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 04:46:03