oxc-project/oxc · error · OxcDiagnostic

State initialization should be in a class property

Error message

State initialization should be in a class property

What it means

Raised by react/state_in_constructor when the rule is configured to prefer class property initializers and state is assigned inside the constructor (`this.state = {...}`). At the throw site the constructor assignment should be a class field (`state = {...}`), the modern idiomatic form that avoids constructor boilerplate. state_in_constructor_diagnostic selects this message when is_state_init_constructor is false, i.e. the state initialization was found in the constructor while the config mandates class-property style.

Source

Thrown at crates/oxc_linter/src/rules/react/state_in_constructor.rs:20

use oxc_diagnostics::OxcDiagnostic;
use oxc_macros::declare_oxc_lint;
use oxc_semantic::NodeId;
use oxc_span::Span;
use serde::Deserialize;

use crate::{
    AstNode,
    ast_util::get_outer_member_expression,
    context::LintContext,
    rule::{DefaultRuleConfig, Rule},
    utils::{AlwaysNever, is_es6_component, is_state_member_expression},
};

fn state_in_constructor_diagnostic(span: Span, is_state_init_constructor: bool) -> OxcDiagnostic {
    let message = if is_state_init_constructor {
        "State initialization should be in a constructor"
    } else {
        "State initialization should be in a class property"
    };
    OxcDiagnostic::warn(message).with_label(span)
}

impl StateInConstructor {
    pub const fn is_always(&self) -> bool {
        matches!(*self.0, AlwaysNever::Always)
    }

    pub const fn is_never(&self) -> bool {
        matches!(*self.0, AlwaysNever::Never)
    }
}

#[derive(Debug, Default, Clone, Deserialize)]
pub struct StateInConstructor(Box<AlwaysNever>);

declare_oxc_lint!(

View on GitHub (pinned to e1e7af627c)

Solutions

  1. Declare state as a class property: state = {...} directly on the class.
  2. Change the rule mode to 'constructor' if constructor initialization is preferred.
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at crates/oxc_linter/src/rules/react/state_in_constructor.rs:20 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of oxc-project/oxc@e1e7af627c (2026-08-20). Data as JSON: /api/errors/48035abcea8c5b2e. Report an issue: GitHub.