Angular中subscribe内async函数丢失this引用问题求助
问题分析与解决方案
async/await 本身不会导致 this 丢失,问题根源在于函数的this绑定机制:普通函数的this指向调用它的上下文,而箭头函数会捕获定义时的类实例作为this,不会随调用场景变化。
具体解决步骤
将类中的方法改为箭头函数定义,替代手动bind的方式:
- 修改
scanearPlano方法
scanearPlano = () => { this.dialogInfoEscanenando = this.dialog.open(InfoEscaneandoComponent); this.dialogInfoEscanenando.afterClosed().subscribe((datosRecibidos) => { if (datosRecibidos) { if(datosRecibidos && datosRecibidos != ''){ this.inputOf = datosRecibidos; this.buscarOF(true); } } }); }
- 修改
buscarOF方法
buscarOF = async (autoPlay: boolean) => { if(this.inputOf){ this.sinOf = false; this.partida = null; this.plano = null; this.inputPlano = ''; const ordf = this.inputOf; try{ const ordenFabricacion = await this.registroActividadService.getOrdenFabricacion(ordf); if(ordenFabricacion){ this.ordenFabricacion = ordenFabricacion; this.inputPedido = this.ordenFabricacion.partida.split("_")[0]; this.inputPartida = this.ordenFabricacion.partida.split("_")[1]; await this.buscarPartida(false); this.inputOf = this.ordenFabricacion.numero; this.plano = this.ordenFabricacion.articulo; this.inputPlano = this.ordenFabricacion.articulo.terminoBusqueda; if(autoPlay){ this.play(true); } }else{ alert("No se ha encontrado la OF " +ordf); } }catch (err){ if (err instanceof Error) { this.showError("Error al intentar acceder a los datos. " + err.name, err.message); } else { this.showError("Error inesperado.", "Ha ocurrido un error desconocido."); } this.ordenFabricacion = null; } }else{ this.inputPedido = ''; this.inputPartida = ''; this.partida = null; this.inputPlano = ''; this.plano = null; } }
- 移除constructor中的手动绑定
constructor(){ // 删除以下两行绑定代码 // this.scanearPlano = this.scanearPlano.bind(this); // this.buscarOF = this.buscarOF.bind(this); }
额外检查
如果buscarPartida也是普通函数定义,建议同样改为箭头函数,避免后续出现类似的this绑定问题。
原理说明
箭头函数在类中定义时,会自动将this绑定到类实例,无论该方法被如何调用,this始终指向当前组件实例,彻底避免了普通函数因调用上下文变化导致的this丢失问题。
内容的提问来源于stack exchange,提问作者Nessarose
相关产品推荐
相关产品推荐

