React JS - Expected to return a value at the end of arrow function ESlint 错误

React JS - Expected to return a value at the end of arrow function ES lint Error

我正在检查环境是开发环境还是生产环境,如果 development 我正在返回模拟数据,否则我正在调用 API 来获取数据。

现在我收到这个 ES lint 错误,

Expected to return a value at the end of arrow function.

我做错了什么?请帮忙

export const getData = (request: any) => {
  if (process.env.NODE_ENV !== 'development') {
    axios.post(EMAIL_DISPUTE_API, { request })
      .then((res) => {
        return res.data;
      })
      .catch((e) => {
        console.log(e);
      });
  } else {
    return emailDisputeMockResponse;
  }
};

需要 return 个语句来始终或从不指定值。

尝试不使用 else bloc

export const getData = (request: any) => {
  if (process.env.NODE_ENV !== 'development') {
    axios.post(EMAIL_DISPUTE_API, { request })
      .then((res) => {
        return res.data;
      })
      .catch((e) => {
        console.log(e);
      });
  }
    return emailDisputeMockResponse;
};

对于你的函数,if block 不 return 值而是 return emailDisputeMockResponse,所以你需要为你的函数声明 return 值类型和return catch 块中的值,就像下面的代码片段

export const getData = async (request: any): Promise<emailDisputeResponse | null> => {
  let result: emailDisputeResponse | null
  if (process.env.NODE_ENV !== 'development') {
    result = await axios.post(EMAIL_DISPUTE_API, { request })
      .then((res) => {
        return res.data;
      })
      .catch((e) => {
        console.log(e);
        return null;
      });
  } else {
    result = emailDisputeMockResponse;
  }
  return result
};