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 React v16.3, getDerivedStateFromProps() was added as a static lifecycle method to prevent unsafe accesses of instance properties.
getDerivedStateFromProps() is bound with null value when it is called by React.

Therefore, when accessing this in the static lifecycle method, a TypeError exception is thrown.

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) {
        if (nextProps.msg && nextProps.msg !== this.state.msg) { // REACT_STATIC_LIFECYCLE_INVALID_THIS alarm because 'this' is 'null' in static method so 'TypeError' occurs at this point when accessing 'this.state'.
            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?