Outside of officially licensed appearances, it would be copyright/trademark infringement and illegal.
Movie studios own the characters in the films. The actors do not.
Unless the actors get specific permission from the studio to appear as their character, it's generally not allowed as someone will get sued over it.
Could Johnny Depp appear in a commercial as a generic pirate or as a generic version of Tonto?
Maybe... but it's iffy territory.
Could Chris Pratt show up in a commercial in his Starlord costume? Not without first getting clearance from Marvel/Disney.
Oh, and for fun, let me point out that it works the other way, too...
If you've ever watched any indie films, you may notice that nothing has brand logos... Crews spend a lot of time making sure that any identifiable branding/packaging is removed because they don't want to get sued for using the brand in the film without permission... not that it's necessarily illegal. Companies can get very protective of their brand image and, if they feel it is maligned, they are likely to get very litigious.
It's also why ET liked the relatively unfamiliar candy Reese's Pieces instead of the much more popular M&Ms... M&M/Mars refused to give Spielberg permission but Reese's was happy for the exposure and benefited greatly from it... and they didn't even pay for it!
There is an exception that applies to copyright under fair use... The most commonly found is the character in satire/parody... though this wouldn't be likely appear in a commercial, it is acceptable to use a copyrighted character to be used if it's clear that it's being done as a parody... the most easy example is when characters appear on shows like Saturday Night Live