gpt4 book ai didi

Redux thunk dispatch 不返回错误

转载 作者:行者123 更新时间:2023-12-01 10:21:54 24 4
gpt4 key购买 nike

我试图从 dispatch 中返回一个 promise,这样我就可以在我的 react 组件中做这样的事情

this.props.dispatch(requestLogin(data))
.then((res) => {
Navigate.toHome()
}).catch((err) => {
this.showErrorMessage()
})

目前我包装了我的 fetch 以重用我在服务器 API 上传递的常见内容并放置一些日志以进行调试。我是这样做的:
export const query = (path, opts) => {

// common config and boilerplates here
// e.g add device id to every api request

return fetch(opts.url, reqOpts)
.then((response) => {

console.log('response received')

if (response.ok) {
return response.json()
} else
console.log('response not ok')})
.then((respData) => {
if (respData.status === true) {
console.log('response success')
return respData
} else {
const errObj = respData
errObj.server = true
throw errObj
}
}).catch((err) => {
console.log('error catched')
if (err.server) {
throw err
}
throw { status: false, errors: { error_code: 'ERR_FATAL', error_msg: 'Something went wrong.' }, err }
})

那么我的 Action 创建者是这样的:
export function requestLogin (data) {
return function (dispatch) {
const opts = {
method: 'POST',
body: data,
}
return query(Paths.OP_USR_LOGIN, opts)
.then((data) => {
data.TYPE = APP_LOGIN
dispatch(resultData)
},
(data2) => {
// the thrown error actually returns here
// this returned value goes to the .then of the dispatch
return data2
},
).catch((err) => {
// this is not executed
return err
})
}
}

正在发生的事情是
this.props.dispatch(requestLogin(data))
.then((res) => {
// the error actually goes here
Navigate.toHome()
}
(err) => {
// not here
}).catch((err) => {
// or here
this.showErrorMessage()
})

最佳答案

首先,重要的是要了解您给出的第二个参数 then(onFulfilled, onRejected) , 即 onRejected , 是另一种要捕获的语法,因此因为它是在 Action 创建器中的捕获之前编写的,所以当查询函数抛出错误时,您会到达那里。这就是不执行 catch 块的原因。 ( read about promise's then )。

onRejected 中发现错误后,它返回一个 promise ,它不再是一个错误( promise 的状态已完成且未被拒绝)。

如果您希望 promise 到达 catch 块,您应该更改您的 Action 创建者:

return query(Paths.OP_USR_LOGIN, opts)
.then((data) => {
data.TYPE = APP_LOGIN
dispatch(resultData)
},
(data2) => {
// the thrown error actually returns here
// this returned value goes to the .then of the dispatch
return new Promise((resolve,reject) => {
reject(data2)
}
})

这将返回一个被拒绝的 promise ,因此它将被 catch 块捕获。

此外,您可以更改
return new Promise((resolve,reject) => {
reject(data2)
}


throw 'error'

或者
Promise.reject(data2)

如果您需要任何进一步的解释,请告诉我。

关于Redux thunk dispatch 不返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51943267/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com