react runtime_error ai_generated true

警告:组件正在将受控输入更改为非受控(或反之)。输入元素不应在受控和非受控之间切换。请在组件的生命周期内决定使用受控还是非受控输入元素。

Warning: A component is changing a controlled input to be uncontrolled (or vice versa). Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.

ID: react/controlled-input-with-null-value

其他格式: JSON · Markdown 中文 · English
88%修复率
85%置信度
1证据数
2023-03-15首次发现

版本兼容性

版本状态引入弃用备注
React 16.8+ active
React 17.0.2 active
React 18.2.0 active

根因分析

输入框的 value prop 在渲染之间从已定义值变为 undefined 或 null(或反之),导致 React 将输入解释为在受控和非受控模式之间切换。

English

An input's value prop changed from a defined value to undefined or null (or vice versa) across renders, causing React to interpret the input as switching between controlled and uncontrolled modes.

generic

官方文档

https://reactjs.org/docs/forms.html#controlled-components

解决方案

  1. Ensure the value prop is always a defined string or number. For example: <input value={state ?? ''} onChange={...} />
  2. If the value is intentionally null, use uncontrolled input with defaultValue and a key to reset: <input key={resetKey} defaultValue={initialValue} />

无效尝试

常见但无效的做法:

  1. Setting value to empty string '' instead of null/undefined 30% 失败

    If the underlying state is null, converting to '' may mask the real issue and cause empty input when user expects null state.

  2. Using defaultValue instead of value 50% 失败

    Switching to uncontrolled mode may break form logic if you need to programmatically update the input value later.

  3. Adding a key prop to force remount 60% 失败

    Remounting the component on every state change defeats the purpose of controlled inputs and may cause performance issues or loss of focus.