反应本机未处理的承诺拒绝p0

时间:2019-07-31 08:26:12

标签: react-native

您好,当我运行我的项目时出现上述错误吗?

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 个答案:

答案 0 :(得分:1)

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

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

请记住,await只是诺言的句法糖。

答案 1 :(得分:0)

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

所以:

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