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

catch块中this为undefined,无法设置signinError的问题排查

问题:Catch块中无法正确设置类属性signinError的问题

你遇到的核心问题是catch回调里的this指向不对,导致你无法正确访问和修改类实例的signinError属性。我们先看你的代码:

@inject(UserService) export class LoginComponent {
  email = '';
  password = '';
  signinError = '';
  constructor(userService) {
    this.userService = userService
  }
  login() {
    console.log(this.signinError);
    this.userService.login(this.email, this.password).catch(function(error) {
      console.log(this.signinError); // 这里的this不是LoginComponent实例
      this.signinError = error.message;
    });
  }
}

问题原因

在JavaScript中,普通的function()作为回调时,它的this指向会根据调用环境改变——在这个catch回调里,this不再指向LoginComponent的实例,而是指向全局对象(严格模式下是undefined),所以你在里面给this.signinError赋值,其实是在给一个不存在的对象(或全局)加属性,完全和类实例的signinError没关系。

三种解决方案

  • 方案一:使用箭头函数(最推荐)
    箭头函数不会绑定自己的this,它会继承外层作用域的this,也就是login方法里的this(即类实例):
login() {
  console.log(this.signinError);
  this.userService.login(this.email, this.password).catch((error) => {
    console.log(this.signinError); // 现在this指向类实例
    this.signinError = error.message;
  });
}
  • 方案二:提前保存this到变量
    在login方法里先把实例的this存到一个变量(比如that或self),然后在回调里用这个变量:
login() {
  const that = this; // 保存实例的this
  console.log(this.signinError);
  this.userService.login(this.email, this.password).catch(function(error) {
    console.log(that.signinError); // 用that访问实例属性
    that.signinError = error.message;
  });
}
  • 方案三:用bind绑定this
    手动把回调函数的this绑定为类实例:
login() {
  console.log(this.signinError);
  this.userService.login(this.email, this.password).catch(function(error) {
    console.log(this.signinError);
    this.signinError = error.message;
  }.bind(this)); // 绑定this为类实例
}

这三种方法都能解决你的问题,其中箭头函数是ES6+里最简洁直观的写法,优先推荐使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:15:51