react runtime_error ai_generated true

警告:一个组件正在将不受控制的输入更改为受控制的输入。这可能是由于值从未定义更改为已定义值引起的。

Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value.

ID: react/controlled-uncontrolled-input-switch

其他格式: JSON · Markdown 中文 · English
92%修复率
87%置信度
1证据数
2023-11-05首次发现

版本兼容性

版本状态引入弃用备注
[email protected] active
[email protected] active

根因分析

输入元素的 value 属性在重新渲染期间从未定义(不受控制)变为已定义值(受控制),或反之,导致 React 意外切换模式。

English

An input element's value prop transitions from undefined (uncontrolled) to a defined value (controlled) or vice versa during a re-render, causing React to switch modes unexpectedly.

generic

官方文档

https://react.dev/reference/react-dom/components/input#controlling-an-input-with-a-state-variable

解决方案

  1. Initialize the state variable to an empty string instead of undefined, and always pass a string to the value prop.
  2. If the value can legitimately be null/undefined, use defaultValue for the initial uncontrolled state and then switch to controlled with a key prop to remount the input.

无效尝试

常见但无效的做法:

  1. Adding a default value to the input via defaultValue prop while keeping value undefined 85% 失败

    defaultValue is only for uncontrolled inputs; mixing it with a value prop that later becomes defined still triggers the warning.

  2. Using a ternary operator to conditionally set value to undefined or a string 90% 失败

    This creates the exact flip-flop between undefined and defined that causes the warning.

  3. Setting the input's value to an empty string by default to avoid undefined 40% 失败

    While this avoids the warning, it may not reflect the intended initial state (e.g., null for optional fields), leading to incorrect UX.