我在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'
}))
)
})
)
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'
}))
)
})
)