无法在函数内设置未定义的 属性

Cannot set property of undefined within a function

我正在使用 vue 在扩展程序的登录页面上设置错误消息,但在 importCreds() 函数中出现错误。

data(){
    return {
    url:'',
    apikey:'',
    error:'',
    }
},
methods:{
    accountSummaryButton(){
        if (localStorage.getItem("accounts") == null)
            this.error = 'There are no available accounts.';
        }
        else
            // STUFF
    },
    saveLogin(event){
        let app = this;
        if (!app.getAccountData(app.url,app.apikey,this.method))
            this.error = 'An error has occurred, please check Url and API Key.';
        else {
            //STUFF
        }
    },
    importCreds(){
        let app = this;
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
            chrome.tabs.sendMessage(
                tabs[0].id,
                {action: "import_creds"},
                function(response) {
                    if (response){
                        app.url = response.affiliateurl
                        app.apikey = response.apikey
                    } else
                        this.error = 'Go to your affiliate site.';
                }
            );
        });
    },
},

我是否缺少在该函数中访问 error 的简单方法?

importCreds 仍然引用原始的 this,但是 chrome.tabs.query({}, function(tabs) {}) 不是。您可以通过将 this 分配给变量 e.g. (let app = this) 来保留该引用,然后使用 app.error.

data () {
    return {
      url: '',
      apikey: '',
      error: '',
    }
},
methods: {
    accountSummaryButton () {
        if (localStorage.getItem("accounts") == null) {
            this.error = 'There are no available accounts.';
        } else {
            // STUFF
        }
    },
    saveLogin (event) {
        let app = this;

        if (!app.getAccountData(app.url,app.apikey,this.method)) {
            this.error = 'An error has occured, please check Url and API Key.';
        } else {
            // STUFF
        }
    },
    importCreds () {
        let app = this;

        chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
            chrome.tabs.sendMessage(
                tabs[0].id,
                { action: "import_creds" },
                function(response) {
                    if (response) {
                        app.url = response.affiliateurl
                        app.apikey = response.apikey
                    } else {
                        app.error = 'Go to your affiliate site.';
                    }
                }
            );
        });
    },
},