this should not be accessed in React static lifecycle methods

  • REACT_STATIC_LIFECYCLE_INVALID_THIS
  • Error
  • High, Medium
  • react

This rule applies when an unbound this is accessed in React static lifecycle methods.

In such a case, a TypeError exception is thrown because React does not provide this value when calling static lifecycle methods.

Noncompliant Code Example

View with compliant examples side by side
import React from 'react';

export class Hello extends React.Component {
  constructor(props) {
    super(props);
    this.state = { msg: 'hi' };
  }
  static getDerivedStateFromProps(nextProps, prevState) {
    // REACT_STATIC_LIFECYCLE_INVALID_THIS alarm because 'this' is 'null' in static method.
    // In this case, a 'TypeError' occurs when accessing 'this.state'.
    if (nextProps.msg && nextProps.msg !== this.state.msg) {
      return { msg: nextProps.msg };
    }
    return null;
  }
  render() {
    return <div>{this.state.msg}</div>;
  }
}

Compliant Code Example

View with noncompliant examples side by side
import React from 'react';

export class Hello extends React.Component {
  constructor(props) {
    super(props);
    this.state = { msg: 'hi' };
  }
  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.msg && nextProps.msg !== prevState.msg) {
      return { msg: nextProps.msg };
    }
    return null;
  }
  render() {
    return <div>{this.state.msg}</div>;
  }
}

Version

This rule was introduced in DeepScan 1.13.0-beta.

See

Was this documentation helpful?