【发布时间】:2022-01-20 03:48:36
【问题描述】:
我对 React-Redux 相对较新,并且面临一个问题,如果我第一次更新减速器参数的状态,它会完美执行,然后如果我用一些不同的值再次执行它会抛出这个我的 try/catch 块中的异常:
Invariant Violation:
A state mutation was detected between dispatches, in the path "object1.object2.0.object3.0.value"
现在我为状态添加了另一个更新,每当它捕获到异常时,在第一个异常之后,状态会相应地更新,并且不会为任何进一步的更新提供任何异常。
以前每次更新调用都会发生这种情况,但在线遵循一些解决方案,现在它仅在第二次更新值时发生。这是我用来更新状态的代码 sn-p。
let tempObject3 = [
{
name : "param1",
value = "",
}
{
name : "param2",
value = "",
}
{
name : "param3",
value = "",
}
];
const component = (props) = {
//this state variable is updated every time there is a change in the form
const [formState, setFormState] = React.useState({
value1 : "",
value2 : "",
value3 : "",
});
const updateState = async () = {
const temp = async () = {
// have used other cloning libraries like just-clone and spread operator and JSON.parse(JSON.stringify(object))
let object2Copy = _.cloneDeep(props.object2);
for(var i=0; i<object2Copy.length; i++)
{
let object2ElementCopy = _.cloneDeep(object2Copy[i]);
if(object2ElementCopy.name === "desiredName")
{
//code for populating tempObject3, with modified data from formState state variable
if('object3' in object2ElementCopy)
{
let object3Copy = _.cloneDeep(object2ElementCopy.object3)
object2ElementCopy = {...object2ElementCopy, object3 : tempObject3}
}
else
{
object2ElementCopy.object3 = tempObject3;
}
object2Copy[i] = object2ElementCopy
}
}
return object2Copy;
}
try
{
props.updateObject2(await temp());
}
catch(e)
{
//update after which no further exceptions are caught
props.updateObject2(await temp());
console.log(e);
}
}
}
这里使用的一些方法和对象通过 MapDispatchToProps 和 MapStateToProps 传递给 props。
该异常仅在我第二次更新时出现,尽管同一个 reducer 在其他组件中工作正常,无需 async 和 await。
是的,我知道逻辑应该在减速器中,但我什至尝试过这样做,但同样的异常一直在发生。我什至在 reducer 中创建了一个新对象来保存只有一个级别的数据,但它仍然给我同样的错误。
【问题讨论】:
-
这里的更新逻辑真的很难遵循。您能否举例说明您自己尝试完成的实际状态更新是什么?
-
嘿@markerikson 我自己解决了这个错误,并得到了其他一些人的帮助。无论如何谢谢:)
标签: javascript reactjs redux react-redux redux-reducers