取消当前正在进行的所有接口请求

需求: 当请求接口过多,功能点切换的时候需要停止之前的请求接口。

实现:

  • axios.ts 实例化拦截器,自动给每个请求注入 controller.signal,并存入 manager
  • 在响应或错误阶段移除 controller

代码实现:

typescript 复制代码
export class RequestManager {
  private controllers = new Set<AbortController>();
  add(c: AbortController) { this.controllers.add(c); }
  delete(c: AbortController) { this.controllers.delete(c); }
  cancelAll(reason = 'Canceled by RequestManager') {
    for (const c of this.controllers) c.abort(reason as any);
    this.controllers.clear();
  }
}
export const requestManager = new RequestManager();
arduino 复制代码
api.interceptors.request.use((config) => {
  // 如果外部已传入 signal,就复用;否则创建新的
  if (!config.signal) {
    const controller = new AbortController();
    config.signal = controller.signal;
    // 把 controller 挂到 config 以便响应阶段访问
    (config as any).__controller = controller;
    requestManager.add(controller);
  } else {
    // 若用户自带 signal,也可选择登记但无法拿到 controller
  }
  return config;
});
typescript 复制代码
api.interceptors.response.use(
  (res) => {
    const controller = (res.config as any).__controller as AbortController | undefined;
    if (controller) requestManager.delete(controller);
    return res;
  },
  (error) => {
    const cfg = error.config || {};
    const controller = (cfg as any).__controller as AbortController | undefined;
    if (controller) requestManager.delete(controller);
    return Promise.reject(error);
  }
);
ini 复制代码
requestManager.cancelAll());
相关推荐
CharlesYu0120 小时前
前端性能优化的第一性原理,是不断缩短“用户发起意图 → 获得可用结果”之间的时间
前端
平头哥技术团队20 小时前
Day 21 _ 页内锚点_给每段起个 id,目录写 href=_#id_,点一下页面就滚到那一段
前端·html·html5
子兮曰21 小时前
Bun v1.4.1 深度解析:从 Zig 到 Rust,一场 11 天、64 个 AI 代理的语言迁徙
前端·后端·bun
人民广场吃泡面21 小时前
什么是AI Agent?它又能给前端带来哪些效率提升?
前端·人工智能
中科三方1 天前
两家域名注册商资质被ICANN终止:企业域名资产安全再受关注
前端·网络·安全·域名
bug总结1 天前
uniapp vue3全局方法注册使用
前端·javascript·uni-app
华无丽言1 天前
如何在宜搭中实现获取子表中的字段值赋值到父表中?
前端·javascript·低代码
IT_陈寒1 天前
Vue的computed属性竟然坑了我一把
前端·人工智能·后端
威斯软科的老司机1 天前
通俗讲解 CNN 图像识别、向量 Embedding、Softmax 概率计算这三块的简化原理
前端·人工智能·ui·数字孪生
2601_962382431 天前
剑指大前端全栈工程师(全2册)主要情节
javascript·实战案例·全栈工程师·剑指大前端·html5+css3