[SalesForce] Storable Action – System.LimitException: Too many DML statements: 1

 @AuraEnabled(cacheable=true)
public static String  deleteContacts(List<String> contactIds) {
    List<Contact> returnList = new List<Contact> ();
    String query = ' SELECT Id,Name, LastName,Department,MobilePhone, Email FROM Contact WHERE id IN : contactIds ';
    for (Contact thisContact:  Database.Query(query)) {
         returnList.add(thisContact);
    }
    try {
      delete returnList;
      return'deleted successfully';
    }
    catch(Exception ex){
       return 'Problem occoured';
    }

}

JS Method
deleteSelected(){
    deleteContacts({
        contactIds :this.selectedIds
    }) 
    .then(result => {
        this.dispatchEvent(
            new ShowToastEvent({
                title: 'Success',
                message: result,
                variant: 'success',
            }),
        );
        return refreshApex(this.getContactList, { searchKeyWord: '$searchKeyWord' });
    })
    .catch(error => {
        this.error = error;
    });

Best Answer

Simply remove the (cacheable=true) parameter from your @AuraEnabled annotation. Caching a delete operation does not make any sense, and is not allowed.


If you read Lightning Components Best Practices: Caching Data with Storable Actions, you will note this section:

The general guideline is to cache (mark as storable) any action that is idempotent and non-mutating.

An idempotent action is an action that produces the same result when called multiple times. For example:

  • getPage(1) is idempotent and should be cached
  • getNextPage() is not idempotent and should not be cached

A non-mutating action is an action that doesn’t modify data. Never cache an action that can create, update, or delete data. For example:

  • updateAccount(sObject) is mutating and not idempotent and should not be cached

Your method violates the non-mutating constraint. It looks like this constraint is a must, rather than a should.