React Native中出现“Accessing object which has been invalidated or deleted”错误求助
Let's break down why you're hitting this error and fix it step by step:
First, the Critical Issue in Your onPress Handler
Looking at your TouchableOpacity code:
onPress={this.deleteData(this.state.t_id)}
This is calling deleteData immediately when the component renders, not when the button is clicked. That means your record gets deleted right as the component loads, and any subsequent attempts to interact with that object (or even re-run this logic) will throw the "invalidated or deleted" error because the object is already gone before you intended to delete it.
Fix this by passing a function reference to onPress instead of invoking the function directly:
<TouchableOpacity style={[styles.BtnSuccess, { flex: 2, flexDirection: 'row' }]} onPress={() => this.deleteData(this.state.t_id)} > <Text style={[styles.btnText, { flex: 1, textAlign: 'center' }]}>Submit</Text> </TouchableOpacity>
This way, deleteData only runs when the button is actually pressed.
Second, Optimize Your Realm Query Logic
Your current code runs the same Realm query twice in the write transaction. While this might seem harmless, it can lead to unexpected state inconsistencies within the transaction. Plus, using string concatenation for your filter ('track_id =' + t_id) is error-prone (e.g., if t_id is a string, you'll miss quotes).
Here's a cleaner, safer version of your deleteData function:
// Use an arrow function to ensure correct `this` binding (no need for constructor binds) deleteData = (t_id) => { realm.write(() => { // Use parameterized filtering to avoid syntax errors and improve safety const trackToDelete = realm.objects('track_info').filtered('track_id = $0', t_id); if (trackToDelete.length > 0) { realm.delete(trackToDelete); console.warn("Record deleted"); Alert.alert( 'Success', 'Deleted successfully'); } else { Alert.alert( 'Error', 'Record not found, or has been deleted already'); } }); }
Key improvements here:
- We store the query result in a variable so we only run the query once.
- Parameterized filtering (
$0) handles all data types correctly without manual string formatting. - Using an arrow function for
deleteDataensuresthisrefers to your component instance (no need to bindthisin the constructor).
Why This Fixes the Error
By fixing the onPress handler, you ensure the delete operation only happens when you intend it to (on button click), not during component render. This prevents accidental early deletion of objects that your code might try to access later. The optimized query logic also reduces the chance of interacting with stale or invalidated Realm objects within the write transaction.
内容的提问来源于stack exchange,提问作者solexadex

