Fix TypeError: Cannot read properties of undefined (reading 'setState') in React
This error occurs when an event handler loses its `this` binding in a class component, making `this` undefined when the handler fires. In function components a similar issue arises when the handler function is stale or incorrectly referenced. Fix it by using arrow functions, binding in the constructor, or converting to a function component with hooks.
Reading the Stack Trace
Here's what each line means:
- at handleSubmit (webpack-internal:///./src/components/LoginForm.tsx:18:10): handleSubmit tries to call this.setState at line 18, but this is undefined because the method lost its binding.
- at HTMLUnknownElement.callCallback (node_modules/react-dom/cjs/react-dom.development.js:4164:14): React's synthetic event system invokes the handler, but the function's this context is not bound to the class instance.
- at executeDispatch (node_modules/react-dom/cjs/react-dom.development.js:9032:3): The event dispatch mechanism calls the handler without preserving the class instance context.
Common Causes
1. Unbound class method
The event handler is a regular class method that is not bound in the constructor, so when React calls it, `this` is undefined.
class LoginForm extends React.Component {
constructor(props) {
super(props);
this.state = { email: '' };
}
handleSubmit(e) {
e.preventDefault();
this.setState({ submitted: true });
}
render() {
return <form onSubmit={this.handleSubmit}><button>Submit</button></form>;
}
}
2. Passing method reference without arrow wrapper
Passing the method directly as a prop to a child component strips the this binding.
class Parent extends React.Component {
handleClick(id) {
this.setState({ selected: id });
}
render() {
return <Child onClick={this.handleClick} />;
}
}
3. Destructuring methods from class instance
Destructuring methods from a class instance creates unbound function references.
const { handleSubmit } = new LoginForm(props);
// handleSubmit is now unbound, calling it loses `this`
The Fix
Convert handleSubmit to a class property arrow function. Arrow functions capture the `this` value from the enclosing scope (the class instance), ensuring it is always correctly bound regardless of how the method is called.
class LoginForm extends React.Component {
constructor(props) {
super(props);
this.state = { email: '' };
}
handleSubmit(e) {
e.preventDefault();
this.setState({ submitted: true });
}
render() {
return <form onSubmit={this.handleSubmit}><button>Submit</button></form>;
}
}
class LoginForm extends React.Component {
constructor(props) {
super(props);
this.state = { email: '', submitted: false };
}
handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
this.setState({ submitted: true });
};
render() {
return <form onSubmit={this.handleSubmit}><button>Submit</button></form>;
}
}
Testing the Fix
import { render, screen, fireEvent } from '@testing-library/react';
import LoginForm from './LoginForm';
describe('LoginForm', () => {
it('renders the submit button', () => {
render(<LoginForm />);
expect(screen.getByRole('button', { name: 'Submit' })).toBeInTheDocument();
});
it('does not crash on form submission', () => {
render(<LoginForm />);
const form = screen.getByRole('button', { name: 'Submit' }).closest('form')!;
expect(() => fireEvent.submit(form)).not.toThrow();
});
it('handles submit event correctly', () => {
render(<LoginForm />);
const form = screen.getByRole('button', { name: 'Submit' }).closest('form')!;
fireEvent.submit(form);
// Component should update state without crashing
expect(screen.getByRole('button')).toBeInTheDocument();
});
});
Run your tests:
npm test
Pushing Through CI/CD
git checkout -b fix/react-event-handler-error,git add src/components/LoginForm.tsx src/components/__tests__/LoginForm.test.tsx,git commit -m "fix: convert handleSubmit to arrow function for correct this binding",git push origin fix/react-event-handler-error
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npm test -- --coverage
- run: npm run build
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
npm install bugstack-sdk
Step 2: Initialize
import { initBugStack } from 'bugstack-sdk'
initBugStack({ apiKey: process.env.BUGSTACK_API_KEY })
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Run the test suite locally to confirm event handlers work with correct binding.
- Open a pull request with the arrow function conversion.
- Wait for CI checks to pass on the PR.
- Have a teammate review and approve the PR.
- Merge to main and verify event handling works in staging.
Frequently Asked Questions
BugStack validates that all event handlers maintain correct this binding, runs your test suite including user interaction tests, and confirms no regressions before marking it safe.
BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.
Function components with hooks avoid this binding issues entirely. If you are actively maintaining the code, converting to hooks is a good long-term investment.
Yes, both create a bound function per instance. Arrow class properties are more concise, but constructor binding is explicit and sometimes preferred in large codebases.