React组件中如何在functionA的Promise内调用functionB?
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:
1. Use Arrow Functions (Recommended)
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

