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

如何在Nuxt 3的useFetch中禁用ofetch自动重试?

在Nuxt 3中让useFetch仅触发一次的解决方案

Nuxt 3的useFetch底层依赖ofetch库,默认失败时会自动重试1次。要实现无论请求结果如何仅触发一次,只需要在请求配置里禁用重试机制即可,有两种方式:

单个请求禁用重试

在调用useFetch时,通过第三个参数的retry选项设置为0,就能让该请求仅执行一次,失败后不再重试:

<script setup>
const { data, error } = await useFetch('/api/your-target-api', {
  retry: 0 // 核心配置:禁用自动重试
})
</script>

全局禁用所有useFetch的重试

如果希望项目中所有useFetch请求都只触发一次,可以在nuxt.config.ts里通过钩子全局配置ofetch的默认选项:

// nuxt.config.ts
export default defineNuxtConfig({
  hooks: {
    'ofetch:options': (options) => {
      // 给所有ofetch请求(包括useFetch)设置默认重试次数为0
      options.retry = 0
    }
  }
})

额外精细控制

如果需要针对特定场景决定是否重试,可以使用retryCondition选项,返回false时就会停止重试:

<script setup>
const { data, error } = await useFetch('/api/your-target-api', {
  retryCondition: (error) => {
    // 示例:仅当错误状态码不是500时才重试,500错误直接终止
    return error.response?.status !== 500
  }
})
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 08:27:37