VueJS与Axios引发'scheduler flush执行错误'及未捕获Promise类型错误
解决思路
1. 先确认组件挂载状态再执行赋值
Cannot read properties of null (reading 'parentNode') 通常是因为异步请求完成后,组件已经被卸载,此时更新treeNodes会触发已不存在的DOM节点更新。可以通过标志位判断组件是否存活:
import { ref, onUnmounted } from 'vue'; const isComponentAlive = ref(true); onUnmounted(() => { isComponentAlive.value = false; }); // 执行请求和赋值 const res = await axios.get('/File'); if (isComponentAlive.value) { treeNodes.value = documentStore.convertToTree(res.data); }
2. 检查convertToTree的返回结构
确认documentStore.convertToTree生成的树结构是否合法,如果返回的节点包含null或未定义的属性,可能导致渲染时找不到对应DOM的父节点。可以在赋值前打印验证:
const res = await axios.get('/File'); const treeData = documentStore.convertToTree(res.data); console.log('生成的树数据:', treeData); // 检查是否有异常节点 treeNodes.value = treeData;
3. 用nextTick延迟DOM更新
Vue的调度器刷新异常可能是因为DOM还未准备完成就触发了更新,把赋值操作放到nextTick中延迟执行:
import { nextTick } from 'vue'; const res = await axios.get('/File'); const treeData = documentStore.convertToTree(res.data); await nextTick(); treeNodes.value = treeData;
4. 避免重复触发异步请求
如果这段代码被频繁调用,会导致Vue调度器冲突。可以用防抖函数限制请求频率:
// 自己实现简易防抖函数 function debounce(fn, delay) { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), delay); }; } const updateTree = debounce(async () => { const res = await axios.get('/File'); treeNodes.value = documentStore.convertToTree(res.data); }, 300); // 调用防抖后的函数 updateTree();
内容的提问来源于stack exchange,提问作者Levyi
相关产品推荐
相关产品推荐

