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

在Promise回调中访问类的其他方法时提示undefined该如何解决?

问题原因
  • fetchResults方法没有显式设置返回值,JavaScript 中无返回值的函数默认返回undefined,因此调用this.fetchResults()得到的结果就是undefined,自然无法调用.then()方法。
  • fetchResults内部直接调用了resolve(),但该变量仅存在于Promise构造函数的回调参数中,你当前的写法会直接抛出resolve is not defined的运行时错误。
修复方案

将fetchResults方法改造为返回Promise实例的形式,把你的异步逻辑封装到Promise内部即可,修改后的参考代码如下:

class Reel {
  constructor(reelContainer, idx, initialSymbols) {
    // some code here
  }

  spin() {
    const animationPromise = new Promise(resolve => this.animation.onfinish = resolve);
    const timeoutPromise = new Promise(resolve => {
      console.log('debug here...');
      console.log(this);
      this.fetchResults().then(() => {
        console.log('got results from the backend...');
        resolve();
      });
    });
    // other code here
  }

  fetchResults() {
    // 返回Promise实例,异步逻辑写在构造回调内
    return new Promise((resolve, reject) => {
      // 此处放置你原本的请求后端、处理结果等逻辑
      // 异步操作完成后调用resolve抛出成功结果
      resolve();
      // 出现错误时可调用reject抛出异常
    })
  }
}

如果你的fetchResults内部本身就是调用其他返回Promise的异步接口,也可以直接返回该异步调用的结果,无需额外包一层Promise。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 09:30:05