this 变量是 Window 对象,或者在 then 方法的 promise 中未定义

The this-variable is the Window object or undefined in the then-method of a promise

本文关键字:方法 then promise 未定义 或者 变量 Window 对象 this      更新时间:2023-09-26

在ES2015(以前的ES6)中,我认为使用箭头语法应该导致this变量成为您所在的对象,从而使旧的var that = this技术过时。

但是,在我的函数中,对于 Promise 的then部分,this变量是Window对象(在 Chrome 中)或undefined(在 FF 和 IE11 中):

import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-http-client';
@inject(HttpClient)
export class InvoiceGenerator {
    items = [];
    constructor(http) {
        this.http = http;
    }
    activate() {
        this.http
            .get(`http://${window.location.host}/api/invoice`)
            .then(response => {
                this.something = response.someProperty; // this is the Window 
            }).catch(err => {
                console.log(err); 
            });
    }
}

顺便说一下,我正在使用Aurelia,以防万一很重要。

如何在不使用旧var that = this技术的情况下让this变量成为我当前所在的对象(我的 Aurelia 视图模型)?

在回调中用"this"引用它之前,你需要在类中声明"something"属性,因为回调中的"this"不包含"something"属性,也不会创建它。

export class InvoiceGenerator {
    something = [];
    constructor(http) {
        this.http = http;
    }
    activate() {
        this.http
            .get(`http://${window.location.host}/api/invoice`)
            .then(response => {
                this.something = response.someProperty; // this is the Window 
            }).catch(err => {
            console.log(err); 
        });
    }
}

我没有尝试过,但我相信打字稿会发现错误。

您是正确的,"箭头语法应引导this变量成为您所在的对象",但您对"在哪个对象"中"感到困惑。执行此操作时:

this.http
  .get(`http://${window.location.host}/api/invoice`)
  .then(response => {
    this.something = response.someProperty; // this is the Window object
  });

它相当于这个:

let thenFn = response => { this.something = response.someProperty; }
this.http
  .get(`http://${window.location.host}/api/invoice`)
  .then(thenFn);

在括号(then(response => ...))内定义函数不会改变您在this.http存在的同一上下文中定义它的事实 - 在您的情况下显然是window

不幸的是,我无法告诉您如何this引用您的Aurelia视图模型,因为您尚未显示视图模型代码或任何其他上下文。