vue router.push Uncaught (in promise) undefined



如果用户已登录,我尝试重定向到另一条路由,但收到此错误。 请帮帮我!

Uncaught (in promise) undefined

我使用 JWT 进行身份验证。

智威登

loginJWT({commit}, payload) {
return new Promise((resolve, reject) => {
jwt.login(payload.userDetails.email, payload.userDetails.password)
.then((response) => {
if (response.data.user_data) {
router.push(router.currentRoute.query.to || '/')
localStorage.setItem('accessToken', response.data.access_token)
commit('updateUserInfo', response.data.user_data, {root: true})
commit('setBearer', response.data.access_token)
resolve(response)
} else {
reject({message: 'Wrong Email or Password'})
}
})
.catch(error => {
reject(error)
})
})
},

单击登录按钮并重新加载页面后,再次单击登录按钮,没有错误。

如果单击登录按钮后未刷新页面,则会发生错误。

您收到此错误,因为您没有处理 promise 错误。

如果处理不当,承诺可能会导致不可预测的错误(尤其是与不必要的回调函数混合时,这里的情况并非如此(。

我在你的代码中看到两个更大的错误:

未处理起始承诺错误/
  • 成功(未处理/未捕获承诺错误(
  • 您在保存用户登录数据之前/期间导航离开(router.push(((

它们都可能给您带来错误,即使您认为自己已经登录。

此外,if/then 条件在承诺链中不是必需的,如果做得好,它可以自行处理。

希望此代码能帮助您更好地理解:

login(formdata)
.then((response) => {
// login response success,
// save the userdata and token
resolve(response) // or return(respone)
})
.then((response) => {
// user data succesfully saved,
// and you can do extra check on it
// safe to navigate away
resolve(reponse) // or return(respone)
})
.catch((error) => {
// anything goes bad,
// you land here with error message
// handle the error
})
.finally(() => {
// if finally() is supported by your login method
// you can decide whats next,
// the promise is fulfilled/rejected
})
// other potential (and often made mistake) to do logic here:
// we are 'after' the login method, but not out of the woods yet
// the promise might be still be unresolved/unrejected = undefined

还有其他方法可以处理承诺:异步/等待尝试/捕获
但是当该方法是"thenable">时,我更喜欢链接它。
更优雅的恕我直言

快乐的承诺!

相关内容

最新更新