Expo环境下React Native使用socket.io-client触发只读属性赋值TypeError报错
报错根因与修复方案
核心触发报错的问题点
- 构造函数逻辑错误:React类组件的
constructor仅用于状态初始化、方法绑定逻辑,不能直接return JSX视图。你将原本应放在render()生命周期中的视图代码写入constructor,强制覆盖了组件构造函数的默认返回值,导致React内部给组件实例挂载updater等内部属性时,触发“对象不可扩展、只读属性赋值”的报错,Web端提示的Cannot add property updater、移动端提示的attempted to assign to readonly property都是这个问题导致的。 - 事件绑定逻辑错误:代码中
onPress={this.connectWifi()}是组件渲染时立即执行connectWifi方法,将方法返回值undefined传给点击事件,并非绑定点击回调。这种渲染阶段提前执行socket初始化逻辑的写法,会和React的状态更新流程冲突,放大报错问题。
其他附带的逻辑缺陷
- 重复导入
socket.io-client模块:同时写了两次同名导入,无实际作用。 - IP输入框未绑定状态:TextInput没有关联state中的ip值,用户输入的内容无法同步到组件状态,连接逻辑永远使用默认的localhost地址。
- 方法未绑定this指向:类组件自定义方法直接在事件中调用时会丢失this上下文,执行时无法正常访问state、props属性。
修复后可正常运行的代码
import React from 'react'; import {View, Text, StyleSheet, TextInput, TouchableHighlight} from 'react-native'; import io from 'socket.io-client'; export default class ConnectScreen extends React.Component{ constructor(props){ super(props) this.state = { ip: "localhost", connecting: false, } // 绑定方法的this指向,避免上下文丢失 this.connectWifi = this.connectWifi.bind(this); } // 视图逻辑移入render方法 render() { return( <View style={styles.container}> <Text style={styles.txt}>Connect to IP:</Text> <TextInput style={{ height: 60, borderColor: 'gray', borderWidth: 1 }} value={this.state.ip} onChangeText={(text) => this.setState({ip: text})} /> <TouchableHighlight style={styles.button} activeOpacity={0.6} underlayColor="#DDDDDD" onPress={this.connectWifi} > <Text style={styles.txt}> CONNECT </Text> </TouchableHighlight> </View> ); } connectWifi(){ // 防止重复创建socket连接 if(this.state.connecting) return; const socket = io("http://"+this.state.ip+":8888", {transports:['websocket']}); this.setState({connecting:true}); console.log("connecting to http://"+this.state.ip+":8888 ..."); socket.on('connection_successful', () =>{ this.props.navigation.navigate('Main', {socket, ip:this.state.ip}); this.setState({connecting:false}); }); // 超时检测逻辑 setTimeout(() =>{ if(this.state.connecting){ this.setState({connecting:false}); socket.disconnect(); console.log("connection failed"); } },3500); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', width: "50%", alignSelf:'center', }, button:{ alignSelf:'center', backgroundColor: "#89cff0", width: "100%", }, txt:{ alignSelf:'center', fontSize: 50, } });
内容的提问来源于stack exchange,提问作者ersi
相关产品推荐
相关产品推荐

