开发者问题收集

React Native 未处理的承诺拒绝 p0

2019-07-31
1299

您好,我在运行项目时出现上述错误,我做错了什么?

import * as WebBrowser from 'expo-web-browser';
import React , {Component} from 'react';
import {PermissionsAndroid} from 'react-native';
import {
    Image,
    Platform,
    ScrollView,
    StyleSheet,
    Text,
    Button,
    TouchableOpacity,
    View,
    Switch
} from 'react-native';
import { MonoText } from '../components/StyledText';
import {Linking , SMS }from 'expo';
import * as Permissions from 'expo-permissions'

class Sendsms extends Component {
    state = {switch1Value: false}

    toggleSwitch1 = (value) => {
        this.setState({switch1Value: value});
        console.log('Switch 1 is: ' + value);

    }

    askSMSPermissionsAsync = async () => {
        await Permissions.askAsync(Permissions.SMS);
    };
    HandlePress = () =>{
        console.log('try to send sms');

    }

    render(){
        return(
            <View>
            <Text>{this.state.switch1Value ? 'Switch is ON' : 'Switch is OFF'}</Text>
            <Switch onValueChange = {this.toggleSwitch1.bind(this)} value = {this.state.switch1Value}/>
        <Button title="sendSMS"  onPress={this.askSMSPermissionsAsync} />
        </View>
    )
    }
}

我尝试重建项目并删除构建文件夹,但没有成功 我还尝试将代码复制到其他项目中,仍然出现同样的错误

export default Sendsms;
2个回答

您需要将 await 调用包装在 try/catch 中,以处理被拒绝的承诺。我不确定它为什么会被拒绝,但您可以通过 console.log 来找出原因:

  askSMSPermissionsAsync = async () => {
    try {
      await Permissions.askAsync(Permissions.SMS);
    } catch(e) {
      console.log(e);
    }
  };

请记住, await 只是承诺的语法糖。

azundo
2019-07-31

await Permissions.askAsync(Permissions.SMS); 导致 Promise 可能被拒绝。使用 Promise 时,请始终使用 try {} catch(e) { 来捕获任何拒绝。 检查日志以获取有关拒绝的更多信息。

因此:

askSMSPermissionsAsync = async () => {
  try {
    await Permissions.askAsync(Permissions.SMS);
  } catch (e) {
    console.error(e);
  }
};
Martijn Coevert
2019-07-31