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

算法交易中TypeError: Cannot read property 'then' of undefined错误排查求助

问题根源:marketBuy()未返回Promise对象

你遇到的「TypeError: Cannot read property 'then' of undefined」错误,核心原因很简单:你的marketBuy()函数没有返回任何Promise对象。虽然函数内部有client.getLatestInformation()和client.placeActiveOrder()这两个异步操作(它们都是Promise),但整个函数执行完后默认返回undefined——你在外部调用exchange.marketBuy().then(...)时,本质是在给undefined调用.then(),自然会报错。

如何修复?

只需要让marketBuy()返回它内部的Promise链即可,这样外部调用时就能拿到一个有效的Promise,进而正常链式调用.then()和.catch()。

修改后的marketBuy()函数

marketBuy() {
  // 1. 返回整个getLatestInformation的Promise链
  return client.getLatestInformation()
    .then(response => {
      var price = response.result[0].last_price;
      // 2. 返回placeActiveOrder的Promise,让结果能传递到外部的then
      return client.placeActiveOrder({
        side: "Buy",
        symbol: "BTCUSD",
        order_type: "Market",
        qty: 20,
        time_in_force: "GoodTillCancel",
        take_profit: price * 1.5,
        stop_loss: price / 1.5
      })
    })
    .then(response => {
      console.log(response);
      return response; // 可选:如果外部需要这个订单响应结果,可以返回它
    })
}

外部调用代码可以保持原样(或简化)

console.log("BUY");
exchange.marketBuy()
  .then(res => {
    console.log("Buy successful");
    hasPosition = true;
    setTimeout(strategy, 1000);
  })
  .catch(console.error); // 现在能捕获marketBuy内部所有Promise的错误了

为什么这样改有效?

  1. 给client.getLatestInformation()前面加上return,让marketBuy()的返回值变成这个Promise对象,外部调用时就能拿到有效的Promise实例。
  2. 在第一个.then()里返回client.placeActiveOrder(...),确保Promise链能把下单操作的结果传递下去,外部的.then()也能感知到下单完成的时机。

这样修改后,不仅能解决你遇到的TypeError,还能让错误处理更完整——marketBuy()内部任何一步异步操作出错,都会被外部的.catch()捕获到。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:31:51