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

useImperativeHandle报错:Cannot add property current, object is not extensible

问题原因及解决方案

你的错误是因为子组件中forwardRef的回调函数参数顺序错误:forwardRef的回调第一个参数是组件的props,第二个才是传递进来的ref。你现在把第一个参数当成了ref,实际上拿到的是props——而React的props是不可扩展的冻结对象,当useImperativeHandle尝试给这个“ref”(实际是props)添加current属性时,就会抛出“Cannot add property current, object is not extensible”的错误。

修正后的子组件代码

import { forwardRef, useState, useImperativeHandle } from 'react';

const Toast = forwardRef((props, ref) => { // 需接收props和ref两个参数,顺序不能错
  const [openToast, setOpenToast] = useState(true);

  useImperativeHandle(ref, () => ({
    show() {
      alert("hello");
    },
  }));

  return (
    <div></div>
  );
});

export default Toast;

父组件代码无需修改

你的父组件写法是正确的,修正子组件后,点击按钮就能正常调用toastRef.current.show()方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 20:00:14