Chazal tell us that even a mitzvah done she’lo lishma has merit. Because Balak offered 42 korbanos, even though done with the wrong intention, he merited to have Rus among his offspring (Nazir 23).
The gemara elsewhere (Brachos 17) seems to present a contrary view, telling us that one who performs a mitzvah shelo lishma should never have been born.
Tosfos reconciles the two statements: even when done without a positive lishma goal in mind, e.g. someone who learns Torah just because he wants to be called Rabbi, the mitzvah still has merit. However, if done for a destructive purpose, e.g. someone learns Torah in order to pick arguments with others, it is better that the mitzvah not be done.
Rav Shach writes that he does not understand how Tosfos’ answer fits the gemara. Balak offered his korbanos in a misguided effort to help Bilam curse the Jewish people. Surely this type of aim should be characterized as a destructive she’lo lishma! Yet, we see that Balak is given credit for his actions.
My son told me that the sefer Chavatzeles haSharon suggests that Tosfos’ distinction applies specifically to the mitzvah of Talmud Torah. The reason Torah study for a destructive purpose counts for nothing is because the subject matter itself, when poisoned with improper intentions, is no longer considered a cheftza shel Torah. Torah studied just to pick fights is not Torah! However, the cheftza of other mitzvos is not defined by intention. A korban offered is a korban offered, regardless of what the person bringing the offering may have in mind.
My problem with this answer is that the language of the gemara speaks of an “osek b’mitzvah" for the wrong reasons not deserving to be born, not just one who learns with destructive intentions. Also, if the Chavatzeles haSharon’s distinction is correct, Tosfos’ should have offered it to resolve the contradiction between gemaras. Tosfos could have explained that Balak gets credit because he performed a mitzvah action, offering a korban, but the gemara which speaks of she’lo lishma having no merit is speaking about Talmud Torah alone.