React中的绑定:未绑定情况下`this`指向何方?
this undefined (or pointing to the global object) in my unbound React class method? Great question—this is one of the most common stumbling blocks when learning React, and it all boils down to how JavaScript handles this binding under the hood, not anything specific to React itself.
Let's break down what's happening in that unbound example you're referencing:
First, the error-prone scenario
Imagine we have a basic class component where we pass an unbound method as an event handler:
class HelloWorld extends React.Component { handleClick() { console.log(this); // What's this value here? } render() { return <button onClick={this.handleClick}>Click Me</button>; } }
What this actually points to
The answer depends on whether strict mode is enabled (which is the default in modern React apps):
- In strict mode (React's default):
thiswill beundefined - In non-strict mode:
thiswill point to the global object (in browsers, that'swindow; in Node.js, it'sglobal)
Why this happens
Here's the core JavaScript rule at play:
Class methods are not automatically bound to the class instance. When you pass this.handleClick to the button's onClick prop, you're just passing a reference to the function itself—not a reference to the function tied to your HelloWorld instance.
When the button is clicked, the browser calls that function as a standalone function (not as yourInstance.handleClick()). In JavaScript, when a function is called without a context (i.e., not as part of an object method), the default binding rule applies:
- Strict mode:
thisbecomesundefined(a safeguard to prevent accidental global variable pollution) - Non-strict mode:
thisfalls back to the global object
This is why you get errors like Cannot read property 'state' of undefined when trying to access this.state in an unbound method—because this isn't pointing to your component instance anymore.
Quick recap
If you don't bind your class method (via constructor binding, arrow function class fields, or inline arrow functions), the method loses its connection to the component instance when called as an event handler. In React's strict mode, that means this is undefined.
内容的提问来源于stack exchange,提问作者tinymarsracing

