【问题标题】:Unexpected token, expected ")" inside axios try-catch statement意外的令牌,预期的“)”在 axios try-catch 语句中
【发布时间】:2021-08-30 08:35:55
【问题描述】:

当我尝试在 try-catch 语句中添加异常 e 的类型为 any 时,我遇到了一个奇怪的问题 Unexpected token, expected ")" 。当 any 类型从 catch 块中删除时,它工作正常。 (显式添加any,因为没有它git管道失败)

 try {
      await axios.patch(
        "/scriptschedule/" + pk + "/",
        postData
      );
      setSubmitting(false);
      afterCreateOrUpdateAction();
    } catch (e: any) {
      setSubmitting(false);
      let message =
        e.response.data && e.response.data.non_field_errors
          ? e.response.data.non_field_errors
          : "Error. Please try again";
      addToast({
        id: "1",
        title: "Error",
        color: "danger",
        text: <p>{message}</p>,
      });
    }

语法对我来说很好。我错过了什么吗?

【问题讨论】:

  • catch ((e: any)) { 这样的东西能修复它吗?
  • @Ashley 不。它会引发解析错误。
  • 啊,查看this PR 似乎表明无法在 catch 子句中注释错误。你的 git 管道抛出了什么具体的错误?
  • @Ashley 非常感谢您分享参考资料。 git 管道在解构e.response.data 时给出了错误Object is of type unknown. TS2571。 .暂时解决了给(e as any).response.data
  • 我会说也许开始考虑永久的临时解决方案。我认为这就是这样做的方法。

标签: reactjs typescript try-catch react-typescript


【解决方案1】:

不能在catch 子句中的错误上添加类型注释。解决这个问题的方法是强制转换变量(我相信你已经这样做了)。

try { 
  // ...
} catch (e) {
  (e as any)...
}

【讨论】:

    猜你喜欢
    • 2020-09-19
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    相关资源
    最近更新 更多