【问题标题】:React Native: Unable to catch thrown errorReact Native:无法捕获抛出的错误
【发布时间】:2020-10-11 01:33:57
【问题描述】:

我试图从我的登录方法中捕获一个错误,然后在我的代码中显示一个警报。我收到一条警告说“未处理的承诺拒绝...”

export default function Login({navigation}){
    
    
    const [email, setEmail]  = React.useState('');
    const [password, setPassword] = React.useState('');
    const [showAlert, setShowAlert] = React.useState(false);
    const [showAlert2, setShowAlert2] = React.useState(false);
    const { signIn } = React.useContext(AuthContext);

    const submit = async() => {

        if (email === '' || password === '') {
            setShowAlert(true);
        } else {
            signIn(email, password).catch(error => 
                setShowAlert2(true)); // THIS NEVER GETS TRIGGERED, WHY?
        }
        
    }

    ...
}

signIn 在我的 App.js 中定义如下:

const authContext = React.useMemo(() => {
    return {
      signIn: (email, password) => {
          auth().signInWithEmailAndPassword(email.email, password.password)
          .then((res) => {
            setIsLoading(false);
            setUser(res.user.uid);
          })
          .catch(error => {
            throw error; // This is the error that should be catched in "submit"
          })
      },
      signUp: () => {
        setIsLoading(false);
        setUser("test");
      },
      signOut: () => {
        setIsLoading(false);
        auth().signOut().then(() => console.log('User signed out!'));
        setUser(null);
      }
    };
}, []);

如您所见,我在某些时候执行“抛出错误”。这就是我想在上面的提交 const 中捕获的错误。

这是我得到的错误:

TypeError: undefined is not an object (evaluating 'signIn(email, password).catch')

【问题讨论】:

    标签: react-native


    【解决方案1】:

    您需要返回那个auth() 调用,然后删除catch,然后错误将传递给signIn 的任何调用

        signIn: (email, password) => {
          return auth() // add return here
            .signInWithEmailAndPassword(email.email, password.password)
            .then(res => {
              setIsLoading(false);
              setUser(res.user.uid);
            })
        },
    

    您甚至可以通过删除花括号并返回来进一步清理它。箭头会自动返回下一个值:

      signIn: (email, password) =>
        auth()
          .signInWithEmailAndPassword(email.email, password.password)
          .then(res => {
            setIsLoading(false);
            setUser(res.user.uid);
          });
    

    您看到的错误基本上是说它在signIn 的返回值上找不到catch 方法。这是真的,因为在您的版本中 signIn 不返回任何内容。 signIn 函数必须返回 一个承诺(它只是一个具有thencatch 等方法的对象);如果您返回一个承诺,那么它将拥有该 catch 方法,然后可以调用该方法。

    【讨论】:

    • 很好的答案,它有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多