Why am I getting the error Maximum call stack size exceeded in Vue Router?

天涯浪子 提交于 2021-01-29 05:30:13

问题


I've eliminated all the ways of 'next' being called twice to prevent loops. Everything seems to work except what's going on inside the if (authenticated) block. The goal is to keep the user stuck at the RegisterFlow page until they've verified & provided a display name. Where am I going wrong?

Error: Uncaught (in promise) RangeError: Maximum call stack size exceeded

Code:

const authPages = ["LoginPage", "Register", "ForgotPass"];
const publicPages = ["PrivacyPolicy", "Terms"];

router.beforeEach(async (to, from, next) => {
  console.log("name", to.name);
  if (!store.state.auth.ready) {
    try {
      await store.dispatch("auth/authenticate");
    } catch (err) {
      console.log("@router err: ", err);
    }
  }

  const authenticated = store.state.auth.authenticationStatus;
  const verified = store.state.auth.verificationStatus;
  let displayName = null;
  if (store.state.auth.user && store.state.auth.user.displayName) {
    displayName = store.state.auth.user.displayName;
  }

  if (publicPages.includes(to.name) || to.name == "Landing") {
    next();
  } else if (authenticated) {
    if (verified && displayName) {
      if (authPages.includes(to.name) || to.name == "RegisterFlow") {
        next("/");
      } else {
        next();
      }
    } else {
      next({ name: "RegisterFlow" });
    }
  } else if (!authenticated) {
    if (authPages.includes(to.name)) {
      next();
    } else if (to.name == "RegisterFlow") {
      next({ name: "LoginPage" });
    } else {
      next({ name: "LoginPage" });
    }
  }
});

回答1:


In this block:

    if (verified && displayName) {
      if (authPages.includes(to.name) || to.name == "RegisterFlow") {
        next("/");
      } else {
        next();
      }
    } else {
      next({ name: "RegisterFlow" });
    }

When someone is not (verified && displayName) you will always trigger a next({name: "RegisteFlow"}) even if to.name == RegisterFlow. This causes the infinite loop. Something like:

    if (verified && displayName) {
      if (authPages.includes(to.name) || to.name == "RegisterFlow") {
        next("/");
      } else {
        next();
      }
    } else {
      if (to.name == "RegisterFlow") { 
         next();
      } else { 
         next({ name: "RegisterFlow" });
      }
    }

will probably do the trick.



来源:https://stackoverflow.com/questions/65602435/why-am-i-getting-the-error-maximum-call-stack-size-exceeded-in-vue-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!