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

为Axios请求实现可取消功能时触发TypeError错误求助

解决Axios旧版本结合OpenAPI生成代码时的可取消Promise configuration 未定义错误

错误根源:this 上下文丢失

你遇到的 TypeError: Cannot read properties of undefined (reading 'configuration'),本质是方法的this指向丢失导致的:
当你直接把 this.api.request 作为参数传给 makeCancellable 时,request 方法的this不再绑定到api实例上。而OpenAPI生成的request方法内部依赖this.configuration获取请求配置,因此调用时会抛出该错误。

两种修复方案

方案一:用bind绑定上下文

在构造函数中,通过bind强制将request方法的this绑定到api实例:

cancellableRequest = makeCancellable(this.api.request.bind(this.api));

方案二:箭头函数包装请求方法

箭头函数会自动捕获当前上下文的this,确保request内部的this指向正确:

cancellableRequest = makeCancellable((...args) => this.api.request(...args));

完整代码示例

假设你的makeCancellable函数结构如下,结合修复后的调用逻辑:

// TypeScript版本的可取消Promise封装
function makeCancellable<T>(promiseFn: (...args: any[]) => Promise<T>) {
  let isCancelled = false;

  const cancellablePromise = (...args: any[]) => {
    return new Promise<T>((resolve, reject) => {
      if (isCancelled) {
        reject(new Error("请求已取消"));
        return;
      }
      promiseFn(...args)
        .then(res => !isCancelled && resolve(res))
        .catch(err => !isCancelled && reject(err));
    });
  };

  const cancel = () => {
    isCancelled = true;
  };

  return { promise: cancellablePromise, cancel };
}

// 服务类中的正确调用
class DataService {
  private cancellableRequest: ReturnType<typeof makeCancellable>;

  constructor(private api: any) {
    // 二选一使用上面的修复方案
    this.cancellableRequest = makeCancellable(this.api.request.bind(this.api));
    // this.cancellableRequest = makeCancellable((...args) => this.api.request(...args));
  }

  async fetchFilteredData(filterParams: any) {
    try {
      const result = await this.cancellableRequest.promise(filterParams);
      // 处理请求结果
    } catch (err) {
      if ((err as Error).message === "请求已取消") {
        // 处理请求取消的逻辑
        console.log("已忽略切换过滤器后的旧请求");
      } else {
        // 处理其他请求错误
      }
    }
  }

  // 切换过滤器时调用此方法取消旧请求
  cancelPendingRequest() {
    this.cancellableRequest.cancel();
  }
}

额外注意事项

  • 切换过滤器时,调用cancelPendingRequest()即可标记旧请求为取消状态,后续返回的Promise结果会被自动忽略。
  • 箭头函数的方案更灵活,能轻松传递所有参数给原request方法,适合参数较多的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 16:32:19