为啥我的 Vue 路由器会抛出最大调用堆栈错误?

Posted

技术标签:

【中文标题】为啥我的 Vue 路由器会抛出最大调用堆栈错误?【英文标题】:Why does my Vue Router throw a Maximum call stack error?为什么我的 Vue 路由器会抛出最大调用堆栈错误? 【发布时间】:2020-04-05 01:44:08 【问题描述】:

我有一个非常简单的路由实际上看起来像这样我在电子下使用它

 import Vue from "vue";
import VueRouter from "vue-router";
import Projects from "../views/Projects.vue";
import RegisterUser from "@/views/RegisterUser.vue";
//import  appHasOwner  from "@/services/";
Vue.use(VueRouter);

const routes = [
  
    path: "/",
    name: "projects",
    component: Projects,
    meta: 
      requiresUser: true
    
  ,
  
    path: "/register",
    name: "register",
    component: RegisterUser
  ,
  
    path: "/settings",
    name: "settings",
    meta: 
      requiresUser: true
    ,
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/Settings.vue")
  
];

const router = new VueRouter(
  mode: "history",
  base: process.env.BASE_URL,
  routes
);

router.beforeEach((to, from, next) => 
  if (to.matched.some(route => route.meta.requiresUser === true)) 
    //this will be for test case undefined
    let user;
    if (typeof user === "undefined") 
      // eslint-disable-next-line no-console
      console.log(user); //logs undefined but at the end no redirect
      next("/register");
     else 
      next();
    
  
);

export default router;

以文档为例

// GOOD
router.beforeEach((to, from, next) => 
  if (!isAuthenticated) next('/login')
  else next()
)

只有当数据库中附加了一个用户时,应用程序才能启动,或者应该重定向到注册组件,但上面的代码将以Maximum call stack size exceeded结尾。那么如何检查beforeEach条件结束重定向到给定页面呢?

【问题讨论】:

【参考方案1】:

Maximum call stack size exceeded 通常是由于无限递归,这里肯定是这样。在router.beforeEach 中,您调用next 以转到/register 路由,该路由返回到此方法,该方法调用next,依此类推。我看到你的meta 中有一个requiresUser,所以你需要在beforeEach 中检查它,如下所示:

router.beforeEach((to, from, next) => 
  // If the route's meta.requiresUser is true, make sure we have a user, otherwise redirect to /register
  if (to.matched.some(route => route.meta.requiresUser === true)) 
    if (typeof user == "undefined") 
      next( path: '/register' )
     else 
      next()
    
  
  // Route doesn't require a user, so go ahead
  next()

【讨论】:

感谢您的反馈,我更新了代码以反映您的建议 @fefe 您还需要在beforeEach 的末尾包含next()。现在你只在第一个 if 块内调用 next()

以上是关于为啥我的 Vue 路由器会抛出最大调用堆栈错误?的主要内容,如果未能解决你的问题,请参考以下文章

为啥完成Activity会抛出NPE?

为啥从主线程调用时,`std::promise::set_value` 会抛出错误?

为啥我的存储过程在包含在事务块中时会抛出错误?

为啥在 V8Js 中运行时,Vue 路由器 beforeEach 中的错误不会抛出异常?

为啥我的自定义 UICollectionViewLayout 在单元格之间添加空格时会抛出错误?

为啥 BufferedStream.Write 会抛出“此流不支持查找操作”?