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

async/await中then()内ViewChild为undefined的问题及原因咨询

补充说明
  • 问题出在async await上。
  • 移除async await,直接返回Promise后问题解决。
  • 不知为何async await内部的then()会丢失类对象的数据,求相关解释,谢谢大家:)

问题描述

在then()回调中使用ViewChild时,它的值为undefined。

代码示例

ViewChild定义

@ViewChild('listaLecturas') listaLecturas!: ITBlistaComponent

HTML代码

<div class="recepcion-lista-lecturas">
    <itb-lista #listaLecturas [entidadActiva]="false" [parametros]="parametrosProductos" [configuracionColumnas]="configuracionProductos" [activarFiltro]="false"></itb-lista>
</div>

方法代码

private async cargarLecturas(): Promise<void> {
    delete this.parametrosProductos['accion']
    this.parametrosProductos['accion'] = 'LEER_RECEPCION_PROMOCION'
    console.log(this.listaLecturas) // 此处已定义

    await this.datos.mantenimiento('LEER_RECEPCION_PROMOCION', this.parametrosProductos)
      .then( (registros) => this.montarLecturas(registros) )
      .catch( (error) => console.log(error))
}

private montarLecturas( registros: any ): void {
    this.listaLecturas.montarRegistros(registros) // 此处为undefined
}

奇怪的是,在then()之前this.listaLecturas是已定义的状态。

调试情况

  • 已定义状态截图
  • undefined状态截图

我尝试过将组件作为参数传入方法:

private async cargarLecturas(): Promise<void> {
    delete this.parametrosProductos['accion']
    this.parametrosProductos['accion'] = 'LEER_RECEPCION_PROMOCION'
    console.log(this.listaLecturas)

    await this.datos.mantenimiento('LEER_RECEPCION_PROMOCION', this.parametrosProductos)
      .then( (registros) => this.montarLecturas(registros, this.listaLecturas) )
      .catch( (error) => console.log(error))
}

private montarLecturas( registros: any, lista: ITBlistaComponent): void {
    lista.montarRegistros(registros)
}

但lista依然是undefined。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 12:45:48