如何设计一个可复用的 useFetch 自定义 Hook?需要考虑哪些边界情况?

解读

在国内 Vue 3 项目里,面试官问“useFetch 怎么写”并不是想听你把 axios 再包一层,而是考察三件事:

  1. 是否真正理解 Composition API 的“状态+副作用”封装思想;
  2. 是否能把网络请求中“加载、错误、重试、竞态、内存泄漏”这些真实场景全部兜底;
  3. 是否具备“业务可配置”意识——让调用方只关心“我要什么”,而不关心“你怎么跑”。
    因此,答案必须给出“可直接拷贝到生产环境”的代码骨架,并逐条说明边界处理的理由。

知识点

  • Composition API:ref、reactive、computed、watchEffect、onScopeDispose
  • 异步竞态(race condition):上一次请求回来得比后一次晚,导致旧数据覆盖新数据
  • 中断与清理:AbortController / AxiosCancelToken
  • 自动重试:指数退避 + 最大次数
  • SSR 安全:只在客户端侧跑副作用
  • 缓存与防抖:同一 key 在 TTL 内直接返回缓存
  • 类型约束:泛型 + TS 严格推断
  • 插件化:拦截器、mock、埋点、错误码统一上报

答案

// src/composables/useFetch.ts
import { ref, computed, unref, watchEffect, onScopeDispose } from 'vue'
import type { Ref, ComputedRef, UnwrapRef } from 'vue'
import axios, { AxiosRequestConfig, AxiosError } from 'axios'

export interface UseFetchOptions<T = unknown> extends AxiosRequestConfig {
  immediate?: boolean          // 是否立即执行
  timeout?: number            // 单次超时
  retry?: number              // 最大重试次数
  retryDelay?: number         // 首次重试间隔(ms)
  onError?: (e: AxiosError) => void
  onSuccess?: (data: T) => void
  cacheKey?: string | ComputedRef<string>  // 缓存主键
  cacheTTL?: number           // 缓存有效期(ms)
}

const cacheMap = new Map<string, { ts: number; data: unknown }>()

export function useFetch<T = unknown>(
  url: string | ComputedRef<string>,
  options: UseFetchOptions<T> = {}
) {
  const {
    immediate = true,
    timeout = 15000,
    retry = 2,
    retryDelay = 500,
    onError,
    onSuccess,
    cacheKey,
    cacheTTL = 5 * 60 * 1000,
    ...axiosConfig
  } = options

  const data = ref<T | null>(null)
  const error = ref<AxiosError | null>(null)
  const loading = ref(false)

  let abortCtl: AbortController | null = null
  let retryCount = 0

  const execute = async () => {
    const targetUrl = unref(url)
    if (!targetUrl) return

    // 1. 缓存命中
    const key = unref(cacheKey) ?? targetUrl
    const cached = cacheMap.get(key)
    if (cached && Date.now() - cached.ts < cacheTTL) {
      data.value = cached.data as UnwrapRef<T>
      return
    }

    // 2. 取消上一次未完成的请求
    abortCtl?.abort()
    abortCtl = new AbortController()

    loading.value = true
    error.value = null

    try {
      const res = await axios.request<T>({
        url: targetUrl,
        timeout,
        signal: abortCtl.signal,
        ...axiosConfig,
      })
      data.value = res.data
      onSuccess?.(res.data)
      // 写缓存
      if (cacheKey) {
        cacheMap.set(key, { ts: Date.now(), data: res.data })
      }
      retryCount = 0
    } catch (e) {
      if (axios.isCancel(e)) return
      error.value = e as AxiosError
      onError?.(e as AxiosError)

      // 3. 指数退避重试
      if (retryCount < retry) {
        retryCount++
        await new Promise(r => setTimeout(r, retryDelay * 2 ** (retryCount - 1)))
        return execute()
      }
    } finally {
      loading.value = false
    }
  }

  // 4. 响应式自动触发
  const stop = watchEffect(() => {
    if (immediate) execute()
  })

  // 5. 组件卸载时清理
  onScopeDispose(() => {
    abortCtl?.abort()
    stop()
  })

  return {
    data: readonly(data),
    error: readonly(error),
    loading: readonly(loading),
    execute,
    abort: () => abortCtl?.abort(),
  }
}

边界情况覆盖清单

  1. 竞态:每次 execute 先 abort 上一次请求;
  2. 重试:指数退避,防止雪崩;
  3. 内存泄漏:onScopeDispose 取消监听与中断请求;
  4. SSR:watchEffect 只在客户端执行,无 DOM 访问冲突;
  5. 缓存:同一 cacheKey 在 TTL 内直接返回,减少并发浪涌;
  6. 类型:泛型 T 自动推断,data 返回值与接口契约一致;
  7. 取消:外部可手动调用 abort(),适用于“搜索框快速输入”场景;
  8. 错误上报:onError 钩子可接入公司统一监控(如 Sentry、阿里 ARMS)。

拓展思考

  1. 分页/下拉加载:把 execute 改造成可接收页码参数,内部维护 list 数组与 hasMore 标志,即可升级为 usePagination。
  2. 串行依赖:在 setup 中先 useFetch 用户详情,拿到 userId 后再 useFetch 订单列表,可用 await + suspense 或 watch 串行,避免“回调地狱”。
  3. 全局拦截:把 axios 实例换成项目级单例,统一加 token、统一错误码映射,useFetch 只负责“触发”与“状态”,实现真正的“零配置”调用。
  4. GraphQL:把 axios 换成 graphql-request,execute 接收 query 与 variables,其余缓存、重试逻辑可完全复用。
  5. 微前端:在 qiankun 子应用卸载时,主应用通过 unmount 钩子调用 abort(),防止子应用销毁后异步回调继续写状态导致主应用白屏。