Skip to content

TypeError: Cannot read properties of null (reading 'setState')

Error message

                Cannot read properties of null (reading 'setState')
              

Quick summary

You called `this.setState()` but `this` is null or undefined, usually because a method wasn't properly bound.

Why this happens

  • Class method passed as callback without binding

  • Used this.method without arrow function or .bind()

  • Called setState in a detached callback

Minimal example

✗ Broken code
class Component extends React.Component {
  handleClick() {
    this.setState({ count: 1 }); // this is undefined!
  }
  render() {
    return <button onClick={this.handleClick}>Click</button>;
  }
}
✓ Fixed code
class Component extends React.Component {
  handleClick = () => {
    this.setState({ count: 1 }); // this is bound
  }
  render() {
    return <button onClick={this.handleClick}>Click</button>;
  }
}

Arrow function class properties automatically bind this to the instance, fixing the undefined this error.

How to diagnose

  • Check how the method is passed to event handlers or callbacks

  • Verify this is bound correctly (arrow function or constructor bind)

  • Log this inside the method

How to fix

  • Use arrow function class properties: handleClick = () => { ... }

  • Bind in constructor: this.handleClick = this.handleClick.bind(this)

  • Use arrow function inline: onClick={() => this.handleClick()}

How to prevent

  • Use arrow function class properties for event handlers

  • Or convert to function components with Hooks

Related Resources

Related Glossary

Related Lessons

← Back to language