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

React中尝试通过Props修改状态报错:无法为只读属性'multiDrag'赋值

解决Cannot assign to read only property 'multiDrag' of object '#'错误

嘿,我一眼就看出问题所在了——你直接修改了React组件的props!在React的设计逻辑里,props是只读的,子组件绝对不能直接修改父组件传过来的props值,这就是你触发这个TypeError的核心原因。

为什么会报错?

this.props是React维护的只读对象,目的是严格保证数据的单向流动:父组件负责控制状态,子组件只接收并使用这些数据。直接给this.props.multiDrag赋值完全违反了这个规则,所以浏览器会抛出"Cannot assign to read only property"的错误。

怎么解决?

你需要把multiDrag的状态控制权交回给父组件(如果这个状态是父组件管理的),或者把它移到当前组件自己的state中(如果状态只属于当前组件),然后通过合法的方式更新:

  • 如果multiDrag是父组件的state:
    父组件需要传递一个回调函数给子组件(比如onUpdateMultiDrag),子组件调用这个函数来通知父组件更新状态,而不是直接修改props。
  • 如果multiDrag只在当前组件使用:
    把它从props迁移到当前组件的state中,用this.setState(类组件)或useState(函数组件)来更新值。

修改你的代码示例

场景1:multiDrag是父组件的状态

假设父组件传递了onSetMultiDrag回调函数,修改后的代码如下:

var finalVal; 
if ( typeof bigFinalValue === "undefined" || bigFinalValue.length < 1 || this.props.singleDrag === true ) { 
    console.log("here he is", this.props.singleDrag); 
    finalVal = <Content>{task.word}</Content>; 
    // 调用父组件的回调更新状态,而非直接修改props
    this.props.onSetMultiDrag(false); 
} 
if ( (typeof bigFinalValue === "undefined" || bigFinalValue.length > 1) && this.props.multiDrag === true ) { 
    console.log("bigFinalValue", bigFinalValue); 
    console.log("selectionCount", selectionCount); 
    console.log("and here he is again..."); 
    finalVal = <Content>{bigFinalValue}</Content>; 
    this.props.onSetMultiDrag(false); 
}

场景2:multiDrag是当前组件的状态

先在组件初始化时把props值同步到本地state,再用setState更新:

// 类组件构造函数中初始化state
constructor(props) {
    super(props);
    this.state = {
        multiDrag: props.multiDrag
    };
}

// 业务逻辑代码
var finalVal; 
if ( typeof bigFinalValue === "undefined" || bigFinalValue.length < 1 || this.props.singleDrag === true ) { 
    console.log("here he is", this.props.singleDrag); 
    finalVal = <Content>{task.word}</Content>; 
    this.setState({ multiDrag: false }); 
} 
if ( (typeof bigFinalValue === "undefined" || bigFinalValue.length > 1) && this.state.multiDrag === true ) { 
    console.log("bigFinalValue", bigFinalValue); 
    console.log("selectionCount", selectionCount); 
    console.log("and here he is again..."); 
    finalVal = <Content>{bigFinalValue}</Content>; 
    this.setState({ multiDrag: false }); 
}

这样就能彻底避免修改只读props的错误,同时完全符合React的单向数据流设计原则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 15:32:26