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

如何在另一个函数中停止$.ajax请求?解决this.xhr未定义问题

解决Ajax请求终止时this.xhr为undefined的问题

问题核心原因

  1. this指向丢失:调用stopFetchData时,this可能未指向类实例,导致无法访问this.xhr。
  2. 前置操作缺失:如果stopFetchData在fetchData之前被调用,this.xhr自然是undefined。
  3. 代码笔误:fetchData方法中使用了未定义的data变量,实际应传入参数scanRequest。

完整解决方案

1. 修正this指向问题

在构造函数中绑定方法的this,避免调用时上下文丢失;或者用箭头函数定义类方法。

2. 完善请求终止逻辑

增加this.xhr的存在性判断,确保调用abort()时不会报错,同时重置xhr实例避免重复操作。

3. 简化冗余代码

$.ajax本身返回Deferred对象,无需额外创建新的$.Deferred。

修正后的完整代码:

class getPostDataController {
    #ajaxApiBaseUrl = "/data/news/post";

    constructor(xhr) {
        this.xhr = xhr;
        // 绑定方法的this指向,确保调用时上下文为类实例
        this.stopFetchData = this.stopFetchData.bind(this);
        this.fetchData = this.fetchData.bind(this);
    }

    fetchData(scanRequest) {
        // 直接返回$.ajax的Deferred对象,无需额外创建
        this.xhr = $.ajax({
            url: this.#ajaxApiBaseUrl + '/scan',
            method: "POST",
            data: scanRequest, // 修正参数变量名
            dataType: "json"
        });
        return this.xhr;
    }

    stopFetchData() {
        console.log('stopScan');
        // 先判断xhr实例是否存在且具备abort方法
        if (this.xhr && typeof this.xhr.abort === 'function') {
            this.xhr.abort();
            // 手动触发reject,让调用方可以捕获请求终止事件
            this.xhr.reject('请求已终止');
            this.xhr = undefined; // 重置xhr实例,避免影响后续请求
        }
    }
}

额外注意事项

  • 如果是在DOM事件(如按钮点击)中调用stopFetchData,不要直接写onclick: controller.stopFetchData,需写成onclick: () => controller.stopFetchData()来保留上下文。
  • 若存在多并发请求场景,需改用数组存储所有xhr实例,终止时遍历数组调用abort()。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 04:20:16