React.js:解决Codesandbox与Firefox中的跨域错误问题
Hey there! Let's break down what's happening here and how to fix it.
First off, that cross-origin error you're seeing is actually a red herring—the real issue is still the TypeError: Cannot read property 'setState' of undefined you expected. React throws this cross-origin message in development mode because browser security rules block it from accessing the actual error object when the error originates from a script hosted on a different domain (like how CodeSandbox serves your app).
How to fix this:
1. Fix the underlying this binding issue (the root cause)
The most common reason for that setState undefined error is that your event handler function isn't bound to the component instance. Here are two easy fixes:
- Use arrow functions for your handlers:
Arrow functions automatically inherit thehandleClick = () => { this.setState({ count: this.state.count + 1 }); }thiscontext from the component, so you won't run into undefined issues. - Bind the function in the constructor:
Once you fix thisconstructor(props) { super(props); this.state = { count: 0 }; // Bind the handler to the component instance this.handleClick = this.handleClick.bind(this); } handleClick() { this.setState({ count: this.state.count + 1 }); }thisbinding problem, the original TypeError will go away, and you won't see that confusing cross-origin error anymore.
2. If you just need to see the real error immediately
If you're stuck and want to bypass the cross-origin message to see the actual error, you can check Firefox's Debugger panel directly—it will show you the full error stack trace, even if React can't access it. For local development setups, you can also configure your dev server to send proper CORS headers, but fixing the this binding is definitely the better long-term solution.
内容的提问来源于stack exchange,提问作者lito

