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

React组件中如何在functionA的Promise内调用functionB?

Solution to Calling functionB Inside Promise Callback in React Component

Hey there! The problem you're facing is related to this context binding in nested function callbacks. When you use regular function() syntax inside canvas.toBlob() and the axios .then() method, the this inside those callbacks doesn't point to your React component instance—so trying to call this.functionB() won't work as expected.

Here are a few clean, reliable ways to fix this:

Arrow functions inherit the this context from their surrounding scope, which in this case is your component's functionA method. This is the most concise and modern approach:

functionA(canvas) { 
  let data = new FormData(); 
  // Replace regular function with arrow function here
  canvas.toBlob((blob) => { 
    data.append('data', blob); 
    axios 
      .post(`https://api.graph.cool/file/v1/${CONST.projectID}`, data, { 
        headers: { 'Content-Type': 'multipart/form-data', }, 
      }) 
      // And here too
      .then((res) => { 
        console.log('res ', res); // res符合预期
        // Now you can call functionB without issues
        this.functionB();
      })
  })
}

2. Save this to a Variable

If you prefer not to use arrow functions, you can store the component's this in a variable (like that or self) at the start of functionA, then use that variable inside the callbacks:

functionA(canvas) { 
  const that = this; // Store the component's this context
  let data = new FormData(); 
  canvas.toBlob(function(blob) { 
    data.append('data', blob); 
    axios 
      .post(`https://api.graph.cool/file/v1/${CONST.projectID}`, data, { 
        headers: { 'Content-Type': 'multipart/form-data', }, 
      }) 
      .then(function(res) { 
        console.log('res ', res);
        // Use the stored variable to access functionB
        that.functionB();
      })
  })
}

3. Bind this to the Callbacks

You can explicitly bind the component's this to each nested function using the .bind() method. This works, but it's a bit more verbose:

functionA(canvas) { 
  let data = new FormData(); 
  canvas.toBlob(function(blob) { 
    data.append('data', blob); 
    axios 
      .post(`https://api.graph.cool/file/v1/${CONST.projectID}`, data, { 
        headers: { 'Content-Type': 'multipart/form-data', }, 
      }) 
      .then(function(res) { 
        console.log('res ', res);
        this.functionB();
      }.bind(this)) // Bind this to the then callback
  }.bind(this)) // Bind this to the toBlob callback
}

All three methods will let you successfully call functionB from inside the Promise callback. The arrow function approach is generally preferred these days because it keeps your code clean and readable.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:03:47