该错误通常出现在使用 ES6 语法时,箭头函数取代了传统的函数,导致上下文丢失。可以使用箭头函数绑定 this 或在声明函数时使用 bind 关键字来解决这个问题。
例如,在使用 subscribe 时,可以使用箭头函数来保持上下文:
this.userService.getUser().subscribe(
(user) => {
this.currentUser = user;
},
(error) => {
console.log(error);
}
);
或者,在声明函数时使用 bind():
this.userService.getUser().subscribe(
function(user) {
this.currentUser = user;
}.bind(this),
function(error) {
console.log(error);
}.bind(this)
);