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

React Query v2环境下如何为useMutation配置失败自动重试3次

实现方案

1. 先实现通用的Promise重试包装函数

/**
 * Promise 重试包装器
 * @param {Function} fn 返回Promise的异步请求函数
 * @param {Number} maxRetries 最大重试次数,默认3次
 * @param {Number} retryDelay 每次重试间隔(毫秒),默认1000ms
 * @returns {Promise} 包装后的Promise
 */
const withRetry = async (fn, maxRetries = 3, retryDelay = 1000) => {
  try {
    return await fn();
  } catch (error) {
    // 可按需增加错误过滤逻辑,比如仅5xx错误/网络错误才重试
    // const shouldRetry = !error.response || (error.response.status >= 500 && error.response.status < 600)
    // if (maxRetries <= 0 || !shouldRetry)  throw error
    if (maxRetries <= 0) {
      throw error;
    }
    await new Promise(resolve => setTimeout(resolve, retryDelay));
    return withRetry(fn, maxRetries - 1, retryDelay);
  }
};

2. 改造现有useMutation代码

只需将原axios请求逻辑用上述withRetry包裹即可,原有onSuccess、onError逻辑无需修改:

const [accessSelectPage, accessSelectPageInfo] = useMutation(
  () => withRetry(() =>
    axios.post(
      POST_ACCESS_SELECT_PAGE_EP(token ?? ''),
      {},
      {
        headers: { 'X-Campaign-ID': campaignID }
      }
    )
  ),
  {
    onSuccess: (responseOnSuccess) => {
      console.log('accessSelectPage', responseOnSuccess)
    },
    onError: (error) => {
      console.log('accessSelectPage error', error)
    }
  }
)

补充说明

  • 默认配置为请求失败后自动重试3次,每次间隔1秒,所有重试都失败后才会触发onError回调
  • 可根据业务需要调整withRetry的第二、第三个入参,自定义重试次数和间隔时长

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:54:02