我在我的React项目中使用redux-observable和axios。我想在调用同一操作时取消api请求。但是我下面的代码似乎并没有取消请求。
const testEpic = action$ => action$.pipe(
ofType('PUT_ACTION'),
mergeMap(action => {
return fromPromise(
axios({
url: 'apiUrl',
data: {},
method: 'put',
headers : getHeaders().toObject(),
})
)
.pipe(
flatMap(response => ({
data,
type: 'PUT_ACTION_SUCCESS',
})),
takeUntil(action$.pipe(
filter(action => action.type === 'PUT_ACTION')
)),
catchError(error => ({
error: error.response,
type: 'PUT_ACTION_ERROR'
}))
)
})
)
答案 0 :(得分:0)
axios不会自动取消请求。因此,必须编写一个CancelToken。 https://github.com/axios/axios#cancellation
const testEpic = action$ => action$.pipe(
ofType('PUT_ACTION'),
mergeMap(action => {
const CancelToken = axios.CancelToken; //cancelToken
const source = CancelToken.source(); //cancelToken
return fromPromise(
axios({
url: 'apiUrl',
data: {},
method: 'put',
headers : getHeaders().toObject(),
cancelToken: source.token //this added
})
)
.pipe(
flatMap(response => ({
data,
type: 'PUT_ACTION_SUCCESS',
})),
takeUntil(action$.pipe(
filter(action => action.type === 'PUT_ACTION’),
tap(ev => source.cancel('canceled')) //do cancel with message
)),
catchError(error => ({
error: error.response,
type: 'PUT_ACTION_ERROR'
}))
)
})
)