Well, here is my opinion;
If you are talking about US, you need to be living here for a year or more and than only you can apply from there. Just having a visa of the country will not give you the right to apply from that country. You need to be working or living with legal status for a year, this is for US, I am sure it goes for all countries as well.
For example, if you live in Dubai, UAE and you are from another country just working there on a multiple work visa, you can still apply from Dubai, you don't need to go to your country to apply.