oxc-project/oxc · error · OxcDiagnostic
State initialization should be in a constructor
Error message
State initialization should be in a constructor
What it means
Raised by react/state_in_constructor when a class component initializes state via `this.state = {...}` inside a method/constructor placement disallowed by the rule's mode: the message variant fires when the rule (configured `always`) requires state to live in the constructor but found the assignment elsewhere. At the throw site assigning this.state outside the constructor bypasses the canonical initialization point and can overwrite constructor-initialized state. state_in_constructor_diagnostic fires from run() with is_state_init_constructor telling which message branch applies.
Source
Thrown at crates/oxc_linter/src/rules/react/state_in_constructor.rs:18
use oxc_ast::AstKind;
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>);View on GitHub (pinned to e1e7af627c)
Solutions
- Move the state assignment into the constructor: this.state = {...} in constructor().
- Change the rule mode to 'class-property' if property initialization is preferred.
Defensive patterns
Strategy: validation
When it happens
Trigger: Thrown at crates/oxc_linter/src/rules/react/state_in_constructor.rs:18 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/a843800a99a92461.
Report an issue: GitHub.