问题
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