简体   繁体   English

TypeError:在函数中使用状态值后,无法分配给对象的只读属性“值”

[英]TypeError: Cannot assign to read only property 'value' of object react after using the value of state in a function

I am trying to develop an E-commerce website with a product detail page .我正在尝试开发一个带有产品详细信息页面的电子商务网站。 Users may select available options of the product.用户可以选择产品的可用选项。 Supposed I choose a shoe and selected size 42 , when I click "Add to Cart" button, it triggers handleAddToCart once.假设我选择了一只鞋子并选择了尺码 42 ,当我单击“添加到购物车”按钮时,它会触发一次handleAddToCart When that is done, if the user wants to add different variations he can just click on differentVariationBox and then again click "Add to Cart" and this should add the newly selected product to cart完成后,如果用户想要添加不同的变体,他只需点击differentVariationBox ,然后再次点击“添加到购物车”,这应该会将新选择的产品添加到购物车

The error comes only after handleAddToCart is executed and handleVariation will cause an error.只有在执行了handleAddToCart之后才会出现错误,并且handleVariation会导致错误。 I would like to know why this error is happening and how to solve it.我想知道为什么会发生这个错误以及如何解决它。

When I try to change the product option I got the following error当我尝试更改产品选项时,出现以下错误

在此处输入图像描述

const handleAddToCart = () => {

  // The selected variation is an array which track the selected attributes but its 
  // order depends on the user click on the attributeswe need to sort them in the order we have 
  // Received from the server because we will create an unique key for the cart item to know if the 
  // Product is alredy in cart with same attributes

  // 😎 example i order shoe with id black-puma with size 42 and color black

  // The id will become black-puma+size=42+color=black now i can track weather this variation product exist

  const order = product.attributes.map((attribute) =>
    this.state.selected_variation.find((v) => v.type === attribute.id)
  );
  
  // Checking if the length of the variation is equal to the length of the attributes
  // This will ensure all the variation is selected
  if (this.state.selected_variation.length ===product.attributes.length) {
    const data = {
      variation: order,
      product: product,
      quantity: this.state.quantity,
      id:`${product.id}+${order.map((item) => `${item.type}=${item.value}`).join("+")}`
    };
    this.props.addToCart(data);
    
  } else {
    alert("Please Select all the variations or The selected variation is already exist in the cart");
  }
};



// Function that will handle the variation selection
    const handleVariation = (e) =>{
      let type = e.target.name;
      let value = e.target.value;

      // Checking is the selected attribute exist
      let index = this.state.selected_variation.findIndex((x)=>{
        return x.type === type
      })
       // if not exist then add it
       if(index === -1){
        this.setState({
          selected_variation: [...this.state.selected_variation, {type,value}]
        })
      }else{
        const newData = [...this.state.selected_variation];
        
        newData[index].value = value
        this.setState({
          selected_variation:newData,
        })
      }
    }

SO Handle variation triggered when SO句柄变化触发时在此处输入图像描述

Any of the variation is change handleVariation will be trigger when there is change in input radio state任何变化都是变化句柄变化将在输入无线电状态发生变化时触发

Problem with your code is here:您的代码有问题:

else{
    const newData = [...this.state.selected_variation];
    
    newData[index].value = value
    this.setState({
      selected_variation:newData,
    })
  }

First, you copied old state using spread.首先,您使用传播复制了旧状态。 Like that you just created new array, but array elements are referencing to that same element from the current state (reference is unmodified since you shallowly copied only array on the top level).就像您刚刚创建了新数组一样,但数组元素正在从当前状态引用相同的元素(引用未修改,因为您仅在顶层浅层复制了数组)。 After that you accessed element with index, and since elements in array were not copied newData[index] reference element directly from this.state .之后,您访问了带有索引的元素,并且由于数组中的元素没有直接从this.state复制newData[index]引用元素。 Since you are trying to mutate state directly react will throw you an error, it won't let you do that because it expect to mutate only using this.setState .由于您尝试直接改变状态,因此 react 会引发错误,因此它不会让您这样做,因为它希望仅使用this.setState进行突变。

Rewrite to this:重写为:

 else{
    this.setState(prevState => ({selected_variation: 
      prevState.selected_variation.map((el, ind) => ind === index ? { ...el, value} : el })
  }

无法分配给 object 的只读属性(值)'#<object> '<div id="text_translate"><p> 我有一个 function 检索 object。</p><pre> const removeLogo = (values: any) =&gt; { values.settings.logoUrl = undefined; setMaster({...values }); };</pre><p> 我的 object 如下:</p><pre> values = { name: "test", reference: "ref" settings: { logoUrl: 'url' } }</pre><p> 在这个 object 我只是想改变一个值:</p><pre> values.settings.logoUrl = undefined;</pre><p> 但我最终收到以下错误消息:</p><pre> form-mail-reminders.tsx:83 Uncaught TypeError: Cannot assign to read only property 'logoUrl' of object '#&lt;Object&gt;'</pre><p> 有没有办法修改object的值而不出现这个错误信息?</p></div></object> - Cannot assign to read only property (value) of object '#<Object>'

无法分配给 # 的只读属性<object>使用带有 Recoil 的 React<div id="text_translate"><p> I'm trying to update my state (an array of objects), but get the above error whenever I try to use.map or edit a clone of the state object.</p><pre> React.useEffect(() =&gt; { setUserMeasurements((oldUserMeasurements) =&gt; { return oldUserMeasurements.map(nameAndMeasure =&gt; { if (nameAndMeasure.name === name) { nameAndMeasure.measure = 60 } return nameAndMeasure; }) })</pre><p> })</p><p> 当我尝试代码的“nameAndMeasure.measure = 60”部分时,它似乎不喜欢它,但我不明白为什么。 谁能解释一下?</p></div></object> - Cannot assign to read only property of #<Object> using React with Recoil

反应 redux,未捕获的类型错误:无法分配给 object 的只读属性“当前”'#<object> '<div id="text_translate"><p> 我正在制作一个网站来修改数据库数据。 一、组件的结构如下</p><pre>&lt;Contents /&gt; &lt;Table /&gt; &lt;Row /&gt; &lt;Column /&gt; &lt;Input /&gt;</pre><p> 创建行组件时,创建输入组件的引用并由 redux 管理它。</p><pre> const StyledRow = styled.div` text-align:center; display:flex; align-items:center; `; const DeleteButton = styled(Button)` background-color: #ff7787; margin-right:5px; color:white; width:40px; ${({top}) =&gt; top &amp;&amp; css` background-color:white; color:white; width:40px; `} `; function Row({top, rowId}){ const dispatch = useDispatch(); const columns = useMemo(() =&gt; columnPhoneInfo,[]); const inputsRef = useMemo(()=&gt;.top &amp;&amp; Array(8).fill(0),map(() =&gt; createRef() );[]); // const inputsRef = useRef([]). useEffect(()=&gt; { // console,log(rowId;top), ;top &amp;&amp; dispatch(phoneDataAddRef(rowId,inputsRef)); }.[]); const handleDeleteButton = useCallback( (id) =&gt; { dispatch(phoneDataUpdate,Delete(id)); }.[]). if( top ) return( &lt;StyledRow&gt; &lt;DeleteButton top/&gt; {columns.map((column)=&gt; &lt;Column key={`head_${column.name}`} width={column;width} top&gt; {column.name} &lt;/Column&gt; )} &lt;/StyledRow&gt; ), return( &lt;StyledRow&gt; &lt;DeleteButton onClick={()=&gt;handleDeleteButton(rowId)}&gt; delete &lt;/DeleteButton&gt; {columns.map((column. index)=&gt; &lt;Column key={`row_${rowId}_${column.name}`} width={column;width} textalign={column.textalign}&gt; &lt;Input ref={inputsRef[index] } colIndex={index} id={rowId} column={column} /&gt; {/* &lt;Input colIndex={index} id={rowId} column={column} /&gt; */} &lt;/Column&gt; )} &lt;/StyledRow&gt; ); } export default React.memo(Row);</pre><p> 输入组件只接收 ref 作为 forwardRef</p><pre> const StyledInput = styled.input` ${({ width, textalign })=&gt;css` width:${width}; text-align:${textalign}; `} `; const Input = forwardRef(({colIndex, id},inputRef) =&gt;{ const dispatch = useDispatch(); const didShowAlert = useRef(false); const nowColumnInfo = columnPhoneInfo[colIndex]; const nowColumnValidCheck = inputValidCheck[colIndex]; const { nowVal, firstVal, isAddedRow } = useSelector(state =&gt;({ nowVal: state.phoneData.data.rows.find(val=&gt;val.id === id)[nowColumnInfo.colname], firstVal: state.phoneData.firstData.lastId &lt; id? null: state.phoneData.firstData.rows.find(val=&gt;val.id===id)[nowColumnInfo.colname], isAddedRow: state.phoneData.firstData.lastId &lt; id? true: false, }),shallowEqual); const callbackDispatch = useCallback((dispatchFunc) =&gt;{ return(...args)=&gt;{ dispatch(dispatchFunc(...args)); } },[dispatch]); ////////////////////// const inputChange = useCallback( (value) =&gt; dispatch(phoneDataUpdate.Change(id,nowColumnInfo.colname, value)),[nowColumnInfo.colname, dispatch, id]); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// const updateListChange = callbackDispatch(phoneDataUpdateList.Change); const updateListDelete = callbackDispatch(phoneDataUpdateList.Delete); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// const handleChange = useCallback( (e) =&gt; { //... todo handle change },[]); ///////////////////////////////////////////////////////// const handleBlur = useCallback( (e) =&gt;{ //... todo handle blur },[]); return( &lt;StyledInput textalign={nowColumnInfo.textalign} width={nowColumnInfo.width} value={nowVal === null? '': nowVal } onChange={handleChange} onBlur={handleBlur} ref={inputRef} // placeholder={} /&gt; ); }); export default React.memo(Input);</pre><p> 最后,redux 模块</p><pre>//////////////////////////////////////////////////////// const PHONE_DATA_DELETE = 'phoneData/PHONE_DATA_DELETE'; //////////////////////////////////////////////////////// const PHONE_DATA_ADD_REF = 'phoneData/PHONE_DATA_ADD_REF'; //////////////////////////////////////////////////////// const dataInitRow = { id:null, model_name:null, machine_name:null, shipping_price:null, maker:null, created:null, battery:null, screen_size:null, storage:null, }; const dataInit = { lastId:null, rows:[], } const initialState = { state:{ loading:false, error:false, }, data:dataInit, refData:[], firstData:dataInit, dataChangeList:{ dataAddList:[], dataDeleteList:[], dataUpdateList:[], }, }; const phoneDataFetchAsync = createPromiseThunk(PHONE_DATA, restAPI.getAllPhoneInfo); //////////////////////////////////////////////////////// const phoneDataAddRef=(id, ref) =&gt;({ type:PHONE_DATA_ADD_REF, id:id, ref:ref, }); const phoneDataUpdateList = ({ Change:(id,colName, value) =&gt; ({ type:PHONE_DATA_UPDATE_LIST_CHANGE, id: id, colName: colName, value: value, }), Delete:(id, colName) =&gt; ({ type:PHONE_DATA_UPDATE_LIST_DELETE, id: id, }), }); //////////////////////////////////////////////////////// export default function phoneData(state = initialState, action){ // console.log(`add: ${state.dataChangeList.dataAddList}, delete: ${state.dataChangeList.dataDeleteList}, change: ${state.dataChangeList.dataUpdateList}`); switch(action.type) case PHONE_DATA_DELETE: return produce(state, draft=&gt;{ console.log(action); const idx = state.dataChangeList.dataAddList.findIndex( val =&gt; val === action.id); if( idx === -1 ) draft.dataChangeList.dataDeleteList.push(action.id); else draft.dataChangeList.dataAddList.splice(idx,1); draft.refData = state.refData.filter(row =&gt; row.id.== action;id). draft.data.rows = state.data.rows.filter(row =&gt;row.id;== action;id): }), //////////////////////////////////////////////////////////////////////////////////////////////////////////// case PHONE_DATA_ADD_REF. return produce(state. draft=&gt;{ draft:refData.push({id,action:id. refs;action;ref}): }); //////////////////////////////////////////////////////////////////////////////////////////////////////////// default, return state, } } export {phoneDataFetchAsync, phoneDataDelete,; phoneDataAddRef, };</pre><p> 问题区域是删除按钮。 当我按下按钮时,就会出现该错误。 但是如果不向 state 添加 ref,则不会发生错误。 或者即使我注释掉底部,也没有错误。</p><pre> draft.data.rows = state.data.rows.filter(row =&gt;row.id.== action;id);</pre><p> 或者注释掉底部</p><pre>draft.refData.push({id:action.id, refs:action.ref});</pre><p> 我今天整天都在尝试修复它,但我不知道出了什么问题。 我该如何解决?</p></div></object> - React redux, Uncaught TypeError: Cannot assign to read only property 'current' of object '#<Object>'

TypeError: 无法分配给 object 的只读属性 '#<object> ' Redux Tool Kit Slice for Firebase Storage REACT NATIVE<div id="text_translate"><p> 您好,我在上传到 firebase 存储后尝试设置我的 downloadUrl,但我似乎无法让它与 Redux 工具包一起使用。 我有一个解决方案,但我宁愿以正确的方式使用它,但我似乎无法弄清楚它是否愿意得到一些反馈</p><pre> incrementByAmount: (state, action) =&gt; { state.value += action.payload },</pre><p> 这是<strong>文档</strong>示例。 我知道数字与对象的工作方式不同,<strong>但如果他们可以像这样改变它,为什么我不能呢?</strong></p><pre> setImageUrl: (state, action: PayloadAction&lt;string&gt;) =&gt; { state.imageUrl = action.payload; },</pre><p> <strong>这就是我所说的</strong></p><pre> const downloadUrl = await FirebaseStorageService.uploadFile( photo, setUploadProgress ); dispatch(setImageUrl(downloadUrl));</pre><p> 这是错误</p><pre>ossible Unhandled Promise Rejection (id: 5): TypeError: Cannot assign to read only property 'imageUrl' of object '#&lt;Object&gt;' TypeError: Cannot assign to read only property 'imageUrl' of object '#&lt;Object&gt;'</pre><p> 提前谢谢你 我在其他地方看到过类似的问题,但我觉得答案不清楚。 我可以直接或不使用 RTK 更改 object 的属性吗?</p></div></object> - TypeError: Cannot assign to read only property '' of object '#<Object>' Redux Tool Kit Slice for Firebase Storage REACT NATIVE

TypeError:无法分配给 object 的只读属性 'statusKnown' '#<object> '<div id="text_translate"><p> 我正在尝试根据我在基于反应 Class 的组件中的道具更新 state 但我收到错误消息</p><blockquote><p> TypeError:无法分配给 object '#' 的只读属性 'statusKnown'</p></blockquote><p> 这是下面的代码</p><pre>componentDidMount(){ this.calClass() } calClass = () =&gt; { console.log(this.props.statusKnown, this.state.active); if (this.props.statusKnown == "deactive") this.setState({ active: false }); else if ((this.props.statusKnown = "active")) this.setState({ active: true }); };</pre><p> 然后在父组件中</p><pre>&lt;Button item={item} categoryID={categoryID} statusKnown={status}/&gt;;</pre><p> 如果反应不允许这件事,那么可能的解决方案是什么?</p></div></object> - TypeError: Cannot assign to read only property 'statusKnown' of object '#<Object>'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 反应 State:未捕获的类型错误:无法读取未定义的属性“值” - React State: Uncaught TypeError: Cannot read property 'value' of undefined 无法分配给 object 的只读属性(值)'#<object> '<div id="text_translate"><p> 我有一个 function 检索 object。</p><pre> const removeLogo = (values: any) =&gt; { values.settings.logoUrl = undefined; setMaster({...values }); };</pre><p> 我的 object 如下:</p><pre> values = { name: "test", reference: "ref" settings: { logoUrl: 'url' } }</pre><p> 在这个 object 我只是想改变一个值:</p><pre> values.settings.logoUrl = undefined;</pre><p> 但我最终收到以下错误消息:</p><pre> form-mail-reminders.tsx:83 Uncaught TypeError: Cannot assign to read only property 'logoUrl' of object '#&lt;Object&gt;'</pre><p> 有没有办法修改object的值而不出现这个错误信息?</p></div></object> - Cannot assign to read only property (value) of object '#<Object>' 无法分配给 # 的只读属性<object>使用带有 Recoil 的 React<div id="text_translate"><p> I'm trying to update my state (an array of objects), but get the above error whenever I try to use.map or edit a clone of the state object.</p><pre> React.useEffect(() =&gt; { setUserMeasurements((oldUserMeasurements) =&gt; { return oldUserMeasurements.map(nameAndMeasure =&gt; { if (nameAndMeasure.name === name) { nameAndMeasure.measure = 60 } return nameAndMeasure; }) })</pre><p> })</p><p> 当我尝试代码的“nameAndMeasure.measure = 60”部分时,它似乎不喜欢它,但我不明白为什么。 谁能解释一下?</p></div></object> - Cannot assign to read only property of #<Object> using React with Recoil 反应 redux,未捕获的类型错误:无法分配给 object 的只读属性“当前”'#<object> '<div id="text_translate"><p> 我正在制作一个网站来修改数据库数据。 一、组件的结构如下</p><pre>&lt;Contents /&gt; &lt;Table /&gt; &lt;Row /&gt; &lt;Column /&gt; &lt;Input /&gt;</pre><p> 创建行组件时,创建输入组件的引用并由 redux 管理它。</p><pre> const StyledRow = styled.div` text-align:center; display:flex; align-items:center; `; const DeleteButton = styled(Button)` background-color: #ff7787; margin-right:5px; color:white; width:40px; ${({top}) =&gt; top &amp;&amp; css` background-color:white; color:white; width:40px; `} `; function Row({top, rowId}){ const dispatch = useDispatch(); const columns = useMemo(() =&gt; columnPhoneInfo,[]); const inputsRef = useMemo(()=&gt;.top &amp;&amp; Array(8).fill(0),map(() =&gt; createRef() );[]); // const inputsRef = useRef([]). useEffect(()=&gt; { // console,log(rowId;top), ;top &amp;&amp; dispatch(phoneDataAddRef(rowId,inputsRef)); }.[]); const handleDeleteButton = useCallback( (id) =&gt; { dispatch(phoneDataUpdate,Delete(id)); }.[]). if( top ) return( &lt;StyledRow&gt; &lt;DeleteButton top/&gt; {columns.map((column)=&gt; &lt;Column key={`head_${column.name}`} width={column;width} top&gt; {column.name} &lt;/Column&gt; )} &lt;/StyledRow&gt; ), return( &lt;StyledRow&gt; &lt;DeleteButton onClick={()=&gt;handleDeleteButton(rowId)}&gt; delete &lt;/DeleteButton&gt; {columns.map((column. index)=&gt; &lt;Column key={`row_${rowId}_${column.name}`} width={column;width} textalign={column.textalign}&gt; &lt;Input ref={inputsRef[index] } colIndex={index} id={rowId} column={column} /&gt; {/* &lt;Input colIndex={index} id={rowId} column={column} /&gt; */} &lt;/Column&gt; )} &lt;/StyledRow&gt; ); } export default React.memo(Row);</pre><p> 输入组件只接收 ref 作为 forwardRef</p><pre> const StyledInput = styled.input` ${({ width, textalign })=&gt;css` width:${width}; text-align:${textalign}; `} `; const Input = forwardRef(({colIndex, id},inputRef) =&gt;{ const dispatch = useDispatch(); const didShowAlert = useRef(false); const nowColumnInfo = columnPhoneInfo[colIndex]; const nowColumnValidCheck = inputValidCheck[colIndex]; const { nowVal, firstVal, isAddedRow } = useSelector(state =&gt;({ nowVal: state.phoneData.data.rows.find(val=&gt;val.id === id)[nowColumnInfo.colname], firstVal: state.phoneData.firstData.lastId &lt; id? null: state.phoneData.firstData.rows.find(val=&gt;val.id===id)[nowColumnInfo.colname], isAddedRow: state.phoneData.firstData.lastId &lt; id? true: false, }),shallowEqual); const callbackDispatch = useCallback((dispatchFunc) =&gt;{ return(...args)=&gt;{ dispatch(dispatchFunc(...args)); } },[dispatch]); ////////////////////// const inputChange = useCallback( (value) =&gt; dispatch(phoneDataUpdate.Change(id,nowColumnInfo.colname, value)),[nowColumnInfo.colname, dispatch, id]); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// const updateListChange = callbackDispatch(phoneDataUpdateList.Change); const updateListDelete = callbackDispatch(phoneDataUpdateList.Delete); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// const handleChange = useCallback( (e) =&gt; { //... todo handle change },[]); ///////////////////////////////////////////////////////// const handleBlur = useCallback( (e) =&gt;{ //... todo handle blur },[]); return( &lt;StyledInput textalign={nowColumnInfo.textalign} width={nowColumnInfo.width} value={nowVal === null? '': nowVal } onChange={handleChange} onBlur={handleBlur} ref={inputRef} // placeholder={} /&gt; ); }); export default React.memo(Input);</pre><p> 最后,redux 模块</p><pre>//////////////////////////////////////////////////////// const PHONE_DATA_DELETE = 'phoneData/PHONE_DATA_DELETE'; //////////////////////////////////////////////////////// const PHONE_DATA_ADD_REF = 'phoneData/PHONE_DATA_ADD_REF'; //////////////////////////////////////////////////////// const dataInitRow = { id:null, model_name:null, machine_name:null, shipping_price:null, maker:null, created:null, battery:null, screen_size:null, storage:null, }; const dataInit = { lastId:null, rows:[], } const initialState = { state:{ loading:false, error:false, }, data:dataInit, refData:[], firstData:dataInit, dataChangeList:{ dataAddList:[], dataDeleteList:[], dataUpdateList:[], }, }; const phoneDataFetchAsync = createPromiseThunk(PHONE_DATA, restAPI.getAllPhoneInfo); //////////////////////////////////////////////////////// const phoneDataAddRef=(id, ref) =&gt;({ type:PHONE_DATA_ADD_REF, id:id, ref:ref, }); const phoneDataUpdateList = ({ Change:(id,colName, value) =&gt; ({ type:PHONE_DATA_UPDATE_LIST_CHANGE, id: id, colName: colName, value: value, }), Delete:(id, colName) =&gt; ({ type:PHONE_DATA_UPDATE_LIST_DELETE, id: id, }), }); //////////////////////////////////////////////////////// export default function phoneData(state = initialState, action){ // console.log(`add: ${state.dataChangeList.dataAddList}, delete: ${state.dataChangeList.dataDeleteList}, change: ${state.dataChangeList.dataUpdateList}`); switch(action.type) case PHONE_DATA_DELETE: return produce(state, draft=&gt;{ console.log(action); const idx = state.dataChangeList.dataAddList.findIndex( val =&gt; val === action.id); if( idx === -1 ) draft.dataChangeList.dataDeleteList.push(action.id); else draft.dataChangeList.dataAddList.splice(idx,1); draft.refData = state.refData.filter(row =&gt; row.id.== action;id). draft.data.rows = state.data.rows.filter(row =&gt;row.id;== action;id): }), //////////////////////////////////////////////////////////////////////////////////////////////////////////// case PHONE_DATA_ADD_REF. return produce(state. draft=&gt;{ draft:refData.push({id,action:id. refs;action;ref}): }); //////////////////////////////////////////////////////////////////////////////////////////////////////////// default, return state, } } export {phoneDataFetchAsync, phoneDataDelete,; phoneDataAddRef, };</pre><p> 问题区域是删除按钮。 当我按下按钮时,就会出现该错误。 但是如果不向 state 添加 ref,则不会发生错误。 或者即使我注释掉底部,也没有错误。</p><pre> draft.data.rows = state.data.rows.filter(row =&gt;row.id.== action;id);</pre><p> 或者注释掉底部</p><pre>draft.refData.push({id:action.id, refs:action.ref});</pre><p> 我今天整天都在尝试修复它,但我不知道出了什么问题。 我该如何解决?</p></div></object> - React redux, Uncaught TypeError: Cannot assign to read only property 'current' of object '#<Object>' TypeError: 无法分配给 object 的只读属性 '#<object> ' Redux Tool Kit Slice for Firebase Storage REACT NATIVE<div id="text_translate"><p> 您好,我在上传到 firebase 存储后尝试设置我的 downloadUrl,但我似乎无法让它与 Redux 工具包一起使用。 我有一个解决方案,但我宁愿以正确的方式使用它,但我似乎无法弄清楚它是否愿意得到一些反馈</p><pre> incrementByAmount: (state, action) =&gt; { state.value += action.payload },</pre><p> 这是<strong>文档</strong>示例。 我知道数字与对象的工作方式不同,<strong>但如果他们可以像这样改变它,为什么我不能呢?</strong></p><pre> setImageUrl: (state, action: PayloadAction&lt;string&gt;) =&gt; { state.imageUrl = action.payload; },</pre><p> <strong>这就是我所说的</strong></p><pre> const downloadUrl = await FirebaseStorageService.uploadFile( photo, setUploadProgress ); dispatch(setImageUrl(downloadUrl));</pre><p> 这是错误</p><pre>ossible Unhandled Promise Rejection (id: 5): TypeError: Cannot assign to read only property 'imageUrl' of object '#&lt;Object&gt;' TypeError: Cannot assign to read only property 'imageUrl' of object '#&lt;Object&gt;'</pre><p> 提前谢谢你 我在其他地方看到过类似的问题,但我觉得答案不清楚。 我可以直接或不使用 RTK 更改 object 的属性吗?</p></div></object> - TypeError: Cannot assign to read only property '' of object '#<Object>' Redux Tool Kit Slice for Firebase Storage REACT NATIVE 将Object.defineProperty与Angular一起使用会引发TypeError:无法分配为仅读取#的属性(属性) <Object> - Using Object.defineProperty with Angular throws TypeError: Cannot assign to read only property (property) of #<Object> 未捕获的TypeError:无法分配为只读对象&#39;#的属性&#39;background&#39; <Object> “ - Uncaught TypeError: Cannot assign to read only property 'background' of object '#<Object>' 未捕获的TypeError:无法分配给对象'#<Object>'的只读属性'exports' - Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>' TypeError:无法分配为只读对象“#”的属性“ exports” <Object> 在ReactJS中 - TypeError: Cannot assign to read only property 'exports' of object '#<Object>' in ReactJS TypeError:无法分配给 object 的只读属性 'statusKnown' '#<object> '<div id="text_translate"><p> 我正在尝试根据我在基于反应 Class 的组件中的道具更新 state 但我收到错误消息</p><blockquote><p> TypeError:无法分配给 object '#' 的只读属性 'statusKnown'</p></blockquote><p> 这是下面的代码</p><pre>componentDidMount(){ this.calClass() } calClass = () =&gt; { console.log(this.props.statusKnown, this.state.active); if (this.props.statusKnown == "deactive") this.setState({ active: false }); else if ((this.props.statusKnown = "active")) this.setState({ active: true }); };</pre><p> 然后在父组件中</p><pre>&lt;Button item={item} categoryID={categoryID} statusKnown={status}/&gt;;</pre><p> 如果反应不允许这件事,那么可能的解决方案是什么?</p></div></object> - TypeError: Cannot assign to read only property 'statusKnown' of object '#<Object>'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM