You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React输入框退格时报错:TypeError: Cannot read properties of null (reading 'value')

解决退格时输入框出现TypeError的问题

问题根源

React的合成事件采用事件池机制:事件对象会在回调执行完成后被回收重用。你在setValues的异步回调里访问e.target时,事件对象已经被清空,e.target变为null,自然读不到value属性。输入字符时未触发该问题是因为同步执行的时机差异,退格操作刚好触发了异步访问回收事件对象的场景。

修复方案

在事件回调的同步阶段先取出并处理输入值,再传入setValues的回调中,避免异步访问已被回收的事件对象。

修改后的代码

调整handleChange函数

const [values, setValues] = useState({
    name: '',
    phoneNo: '',
    city: '',
    country: '',
    postcode: '',
    address: '',
});

const handleChange = input => e => {
    // 同步阶段先获取处理后的值
    const inputValue = e.target.value.trim();
    setValues(v => ({ ...v, [input]: inputValue }));
};

输入框组件代码保持不变

<Form.Field required>
    <label>
        {intl.formatMessage({
            id: 'name_label',
            defaultMessage: 'Venue Name',
        })}
    </label>
    <input
        autoComplete="off"
        placeholder={intl.formatMessage({
            id: 'name_label',
            defaultMessage: 'Venue Name',
        })}
        onChange={handleChange('name')}
        defaultValue={name}
    />
</Form.Field>

内容的提问来源于stack exchange,提问作者Alk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 14:40:34