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

如何为createAsyncThunk的请求添加节流控制?

多个图表组件并发请求触发429错误的处理问题

我有一个图表组件,接收props后自动获取数据并渲染。但应用中同时渲染多个该组件时,会发起大量并发请求,触发429(请求过多)错误。

我用createAsyncThunk(在ChartSlice.js中)处理请求,但没法给它加节流。尝试过写中间件,但过滤action时只能看到.../pending、.../fulfilled、.../rejected这些状态的action,没法直接拦截原始的请求触发动作。

我考虑过在父组件统一处理所有请求,但为了保证组件复用性,更希望让图表组件自己处理逻辑,只需要传入props就能自动渲染。


现有代码

父组件

platforms.map((platform) => <ChartComponent platform={platform}/>)

图表组件(多处复用)

export const ChartComponent = memo(({ platform }) => {
  const data = useSelector((state) => state[platform]);
  useEffect(() => {
      dispatch(fetchchart({ platform }));
    }
  }, [platform]);

  return (
    <>
      <ApexChart data={data} />
    </>
  );
});

请求Thunk

export const fetchchart = createAsyncThunk(
  "chart/fetch",
  async (params, thunkAPI) => {
    const response = await fetch(endpoint(params));
    const data = await response.json();
    thunkAPI.dispatch(
      updateChart({data}));
  }
);

临时解决方案

目前还没找到不用提取图表组件逻辑,就能给createAsyncThunk请求加节流的方法。不过我通过给dispatch加超时,并判断请求完成状态,解决了429错误:

useEffect(() => {
  if (chartLoaded === "succeeded") {
    setTimeout(() => dispatch(fetchchart({ platform })), 1000);
  }
}, [platform]);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 19:15:12