“Warning: Render methods should be a pure function of props and state; triggering nested component updates from render is not allowed. If necessary, trigger nested updates in componentDidUpdate. ”
这里提供一种排查方案:这个问题可能会在开发环境中才会出现,如果你的项目中使用了mobx,并且在render中使用了computed,请检查render函数中所使用的computed函数中是否意外执行了副作用。如果有,请放在reaction或者autorun中执行。
今天看一个项目的过程中,程序意外报了个render不是纯函数的警告,但是我没有发现在render中执行了副作用,这个警告让我困惑了两天,把我给整神了。
什么是副作用? 类似DOM操作,修改状态等等。
随便举个例子:
@computed get isStringArrEmpty() {
//类似dom操作都是副作用,或者修改了当前mobx中某个observable的值
const h2 = document.querySelector("h2");
if (h2) {
if (h2.getAttribute("class")) {
h2.removeAttribute("class");
} else {
h2.setAttribute("class", "hide");
}
}
return this.stringArr.length > 0;
}
把副作用放在reaction即可解决:
@computed get isStringArrEmpty() {
return this.stringArr.length > 0;
}
reaction(
()=>this.isStringArrEmpty,
(isStringArrEmpty)=>{
//副作用放在这里完美解决
const h2 = document.querySelector("h2");
if (h2) {
if (h2.getAttribute("class")) {
h2.removeAttribute("class");
} else {
h2.setAttribute("class", "hide");
}
}
}
)