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

如何批量取消Axios实例发起的全部请求?

一次性取消Axios实例所有请求的实现方案

第一步:改造Axios实例配置(dataLayer文件)

给全局Axios实例添加请求追踪机制,把所有未完成请求的取消令牌存起来,再提供一键取消的方法:

import axios from 'axios';

const LcAPI = axios.create();

// 存储所有未完成请求的取消令牌源
const activeCancelSources = [];

// 请求拦截器:每个请求发起前自动生成取消令牌并加入追踪列表
LcAPI.interceptors.request.use(config => {
  const cancelSource = axios.CancelToken.source();
  config.cancelToken = cancelSource.token;
  activeCancelSources.push(cancelSource);
  return config;
});

// 响应拦截器:请求完成(成功/失败)后,移除对应的取消令牌
LcAPI.interceptors.response.use(
  response => {
    const sourceIndex = activeCancelSources.findIndex(source => source.token === response.config.cancelToken);
    if (sourceIndex !== -1) {
      activeCancelSources.splice(sourceIndex, 1);
    }
    return response;
  },
  error => {
    // 主动取消的请求也同步移除令牌
    if (axios.isCancel(error)) {
      const sourceIndex = activeCancelSources.findIndex(source => source.token === error.message.token);
      if (sourceIndex !== -1) {
        activeCancelSources.splice(sourceIndex, 1);
      }
    }
    return Promise.reject(error);
  }
);

// 新增一键取消所有请求的方法
LcAPI.cancelAll = () => {
  activeCancelSources.forEach(source => {
    source.cancel('所有请求已被取消');
  });
  // 清空列表避免重复取消
  activeCancelSources.length = 0;
};

export default LcAPI;

第二步:调整仓库请求逻辑(兼容原有单个请求限制)

如果要保留「单个端点同时只能有一个请求」的逻辑,可以在仓库里单独维护该端点的取消令牌,同时兼容全局追踪:

import LcAPI from './dataLayer';
import axios from 'axios';

class SomeRepository {
  // 存储当前端点的请求取消源(保留原有单个请求限制)
  private static currentDataCallSource: axios.CancelTokenSource | null = null;

  static async getData(
    queryParam1: number,
    queryParam2: number,
    requestBody: RequestBody
  ): Promise<ResponseBody> {
    // 取消当前端点的上一次请求
    if (this.currentDataCallSource) {
      this.currentDataCallSource.cancel('Only one request allowed at a time.');
      // 从全局追踪列表移除该源
      const sourceIndex = activeCancelSources.findIndex(source => source === this.currentDataCallSource);
      if (sourceIndex !== -1) {
        activeCancelSources.splice(sourceIndex, 1);
      }
    }

    // 创建新的取消源
    this.currentDataCallSource = axios.CancelToken.source();

    try {
      const result = await LcAPI.post(
        url,
        requestBody,
        {
          ...getHeaderConfig(),
          // 用当前端点的取消源替换全局的,实现单个端点请求限制
          cancelToken: this.currentDataCallSource.token
        }
      );
      // 请求成功后清空当前源
      this.currentDataCallSource = null;
      return result.data;
    } catch (error) {
      console.log('Error on getPatternTrips API call : ' + error);
      // 主动取消的请求清空当前源
      if (axios.isCancel(error)) {
        this.currentDataCallSource = null;
      }
      throw error;
    }
  }
}

第三步:一键取消所有请求

需要一次性终止所有未完成请求时,直接调用:

LcAPI.cancelAll();

关键说明

  • 全局的activeCancelSources数组会自动清理已完成的请求令牌,不会造成内存泄漏。
  • 单个端点的取消逻辑和全局取消互不冲突,既能单独限制单端点请求,也能一键终止全部请求。
  • 取消请求后,未完成的请求会进入catch块,用axios.isCancel(error)可判断是否为主动取消的错误,方便后续处理。

内容的提问来源于stack exchange,提问作者Md. Arshad Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 17:45:39