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

Vue.js中methods的http请求内this无法使用的原因咨询

问题原因及解决方案

问题出在你forEach循环里使用的普通函数上:
普通function(entry)会创建独立的作用域,这个函数内部的this不再指向Vue组件实例,而是指向函数自身(非严格模式下可能指向全局对象),所以你无法通过它访问到this.rows。

你外层then回调用箭头函数是正确的——箭头函数不会绑定自己的this,会继承外层作用域的this(也就是Vue组件实例),但内层forEach的普通函数打破了这个指向链。

两种修复方法:

  1. 把forEach的普通函数换成箭头函数
    箭头函数会继承外层的this,直接就能访问Vue实例的属性:
methods: {
    setIdFeed(id_feed) {
        this.id_feed = id_feed;
    },
    getImportList() {
        http.get("projects/import/" + this.project_token + '/' + this.user_id)
        .then((response) => {
            if( Object.keys(response.data).length !== 0 ) {
                // 替换为箭头函数
                response.data.forEach((entry) => {
                    this.rows.push({
                        id_feed : entry.id_feed,
                        feed_name: entry.feed_name + " (" + entry.feed_type + ")",
                        tpi: '',
                        status: entry.status,
                    });
                });
            }
        })
        .catch((error) => {
            console.log(error);
        });
    }
},
  1. 提前保存Vue实例的this到变量
    在forEach外部把组件实例的this存为变量,比如vm,然后在循环里用这个变量访问属性:
methods: {
    setIdFeed(id_feed) {
        this.id_feed = id_feed;
    },
    getImportList() {
        http.get("projects/import/" + this.project_token + '/' + this.user_id)
        .then((response) => {
            if( Object.keys(response.data).length !== 0 ) {
                // 提前保存组件实例的this
                const vm = this;
                response.data.forEach(function (entry) {
                    vm.rows.push({
                        id_feed : entry.id_feed,
                        feed_name: entry.feed_name + " (" + entry.feed_type + ")",
                        tpi: '',
                        status: entry.status,
                    });
                });
            }
        })
        .catch((error) => {
            console.log(error);
        });
    }
},

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 20:54:19