ReactJS中window.fetch()未处理Promise拒绝错误的修复方案
已用catch()捕获错误仍出现UnhandledPromiseRejection错误,如何修复?
错误信息
node:internal/process/promises:246 triggerUncaughtException(err, true /* fromPromise */); ^ [UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "Error: FetchError: invalid json response body at undefined reason: Unexpected end of JSON input".] { code: 'ERR_UNHANDLED_REJECTION' }
对应代码
addPokemonToList = () => { window .fetch('/all/pokemons', { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ pokemon_id: this.props.pokemonId, trainer_id: this.props.trainerId, search_id: this.props.searchId ? this.props.searchId : undefined, [getCsrfParam()]: getCsrfToken(), }), }) .then(resp => resp.json()) .then(json => this.setState({ success: json.success, PokemonChoiceId: json.pokemonChoiceId, }) ) .catch(err => { throw new Error(err); }); };
问题根源
你的catch块里重新抛出了错误,这个新抛出的错误没有被任何后续代码捕获,导致Promise链最终还是处于拒绝状态,触发了未处理的Promise拒绝错误。
修复方案
方案1:移除catch内的throw,改为处理错误
把catch块里的throw语句替换成实际的错误处理逻辑,比如打印错误信息、更新组件状态提示用户:
.catch(err => { console.error('添加宝可梦失败:', err); this.setState({ success: false, error: '添加失败,请稍后重试' }); });
方案2:若需保留抛出逻辑,确保后续有捕获
如果确实需要在catch里抛出错误(比如让上层逻辑处理),要在链式调用末尾再加一个catch来捕获这个新错误:
.catch(err => { throw new Error(err); }) .catch(globalErr => { console.error('全局错误捕获:', globalErr); });
不过这种场景很少见,通常直接在第一个catch里处理错误更合理。
修改后的完整代码示例
addPokemonToList = () => { window .fetch('/all/pokemons', { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ pokemon_id: this.props.pokemonId, trainer_id: this.props.trainerId, search_id: this.props.searchId ? this.props.searchId : undefined, [getCsrfParam()]: getCsrfToken(), }), }) .then(resp => resp.json()) .then(json => this.setState({ success: json.success, PokemonChoiceId: json.pokemonChoiceId, error: null }) ) .catch(err => { console.error('请求失败:', err); this.setState({ success: false, error: '添加宝可梦失败,请检查网络或稍后重试' }); }); };
内容的提问来源于stack exchange,提问作者valcod3r
相关产品推荐
相关产品推荐

